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
?
4
Answers
you can pass it as a props in
Layout
:and in
NotSignedInHero
:You pass it as a property. So
and in NotSignedInHero:
Edit: I think I understand after your comment. The passed variable is changed in the Layout component, and you need to pass it first up to the App component and then down to NotSignedInHero. If the variable is changed in a function inside Layout, you can do it like this:
Then is the App component you do this:
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
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.
You can pass props to children by using cloneElement().
See more: https://react.dev/reference/react/cloneElement