React.cloneElement with deeply nested component

116 Views Asked by At

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>
  );
}
0

There are 0 best solutions below