Search code examples
reactjsreact-hookssetstatechildren

React.js, I can't pass a state from a parent component to a child component


I have a react app that consists of a Layout component and everything else is wrapped in this layout.

I have an App.tsx file and the return part of the code looks like this:

return (
  <Layout>
    <div className='App'>
      {isConnected ? <SignedInHero /> : <NotSignedInHero />}
      <br />
      <br />
    </div>
  </Layout>
)

I'm trying to pass a state from the Layout component to the NotSignedInHero component. The return part of the Layout code looks like this:

return (
    <div>
        {isValid ? null : <Placeholder />}
        {isValid ? <Navbar /> : null}
        {isValid ? children : null}
    </div>
)

So if I had a useState variable like const [passed, setPassed] = useState('pass this'): How would I send it from Layout to NotSignedInHero?


Solution

  • There are multiple ways to pass down props to child components. It depends a lot on the type and size of the project and which solutions to choose.

    The simplest solution is passing the prop down to child components using a render function. I personally don't like this as much, but it does the trick without needing dependencies or creating a global state/context.

    Layout.jsx

    const Layout = ({ children }) => {
      const [passed, setPassed] = useState('pass this') ;
    
      return (
        <div>
            {isValid ? null : <Placeholder />}
            {isValid ? <Navbar /> : null}
            {isValid ? children({ passed }) : null} // <-- note that the `children` prop is a function
        </div>
      );
    }
    
    return (
      <Layout>
        {({ passed }) => (
          <div className='App'>
            {isConnected ? <SignedInHero /> : <NotSignedInHero passed={passed} />}
            <br />
            <br />
          </div>
        )}
      </Layout>
    )
    

    The second option is to use React Context, which enables having a global state without needing to do "prop drilling".

    The third option is to use a global state management tool like Zustand.