How to access variable from parent component using JSX Namespacing in React

Viewed 26

I want to pass variable from parent component to props.children

Is posible if I access parent variable to props.children like this?

function App() {
  return (
    <div>
      <Example>
        <Example.Title>
          <p>this is Title</p>
        </Example.Title>
        <Example.Body>
          <p>this is Body</p>
          <p>value from {parent}</p>
        </Example.Body>
      </Example>
    </div>
  );
}

export default App;

Parent Component

import { useState } from "react";

function Example(props) {
  const [parent, setParent] = useState("parent");

  return <div>{props.children}</div>;
}

Example.Title = (props) => <>{props.children}</>;
Example.Body = (props) => <>{props.children}</>;

export default Example;
1 Answers

You can't do it like this, because Example.Body component is already rendered when passed from App to Example.

Example must pass the "parent" prop to Example.Body

One solution is to use children as a render props (see it working there):

export default function App() {
  return (
    <div>
      <Example>
        {(parentParam) => (
          <>
            <Title>
              <p>this is Title</p>
            </Title>
            <Body>
              <p>this is Body</p>
              <p>value from {parentParam}</p>
            </Body>
          </>
        )}
      </Example>
    </div>
  );
}

function Example(props) {
  const [parent, setParent] = useState('parent');

  return <div>{props.children(parent)}</div>;
}
Related