0

it's very complicated to explain the whole use-case here because I have deeply nested component, but I will try to show the concept.

How to display age from parent in OneMoreNestedChild without ContextApi, is it possible in the following example ?

Codesandbox

import React from "react";
import "./styles.css";

const OneMoreNestedChild = ({ age }) => {
  return (
    <>
      <p>One more nested child</p> Age: {age}
    </>
  );
};

const NestedChild = ({ children }) => {
  return (
    <>
      <p>Nested children</p> {children}
    </>
  );
};

const Child = ({ children }) => {
  return (
    <>
      <p>Child</p> {children}
    </>
  );
};

const Parent = ({ children }) => {
  const newChildren = React.Children.map(children, (child) =>
    React.cloneElement(child, { age: 1 })
  );

  return <div>{newChildren}</div>;
};

export default function App() {
  return (
    <div className="App">
      <Parent>
        <Child>
          <NestedChild>
            <OneMoreNestedChild />
          </NestedChild>
        </Child>
      </Parent>
    </div>
  );
}
Mile Mijatović
  • 2,948
  • 2
  • 22
  • 41
  • I guess it is possible to display the age from the parent component in the OneMoreNestedChild component without using the Context API. One way to do this would be to pass the age as a prop to the OneMoreNestedChild component when it is being rendered inside the NestedChild component. – Mohsin Mehmood Dec 04 '22 at 14:41
  • That's correct, but then I will have unnecessary re-render in components which only forwarding the props? – Mile Mijatović Dec 04 '22 at 14:44
  • Yes, using React.cloneElement() in this way will cause the components between the Parent and the OneMoreNestedChild to re-render every time the Parent component updates. This is because React.cloneElement() creates a new component instance with the updated props, and this new instance will be passed down to the child components. Since the child components will receive a new instance of the OneMoreNestedChild component, they will re-render whenever the Parent component updates. – Mohsin Mehmood Dec 04 '22 at 14:47
  • If you want to avoid unnecessary re-renders in the intermediate components, you can use the React.forwardRef() API to create a forwardRef that passes the age prop directly to the OneMoreNestedChild component. This will allow the Parent component to pass the age prop directly to the OneMoreNestedChild component, without needing to create a new component instance or causing the intermediate components to re-render. – Mohsin Mehmood Dec 04 '22 at 14:48
  • I don't understand you how to pass .forwardRef() – Mile Mijatović Dec 04 '22 at 14:51
  • see the answer I have mentioned below – Mohsin Mehmood Dec 04 '22 at 14:53

0 Answers0