Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share state between child component (siblings) in ReactJS?

I would like to pass state to a sibling or even a grandparent whatever.

I have 3 components. Inside Header, I have a button with an onClick function to toggle a Dropdown Menu inside Navigation. And by the way, I would like to pass the same state to AnotherComponent.

How to pass state (such as isDropdownOpened) from Header to Navigation and AnotherComponent?

<div>
     <Header />
       <Navigation />
        <div>
          <div>
             <div>
               <AnotherComponent />
             </div>
           </div>
        </div>
</div>
like image 516
Steffi Avatar asked Dec 06 '18 09:12

Steffi


People also ask

How do you pass state between sibling components React?

To move data from a component to a sibling component, the simplest way is to pass a function from the parent component as a prop (i.e. "prop function") to its child that wants to update the data.

How do you share data between two child components in React?

First, you'll need to create two components, one parent and one child. Next, you'll import the child component in the parent component and return it. Then you'll create a function and a button to trigger that function. Also, you'll create a state using the useState Hook to manage the data.

Can you pass state from child to parent React?

To pass data from child to parent component in React:Pass a function as a prop to the Child component. Call the function in the Child component and pass the data as arguments.

How do you pass state value from one component to another?

Passing State to a Component To pass the state into another component, you can pass it as a prop. Then, inside <ExampleComponent /> , you can access the data as this. props. data .


1 Answers

You have different approaches to address this situation.

  • Keep the state in the top component and pass it to children through props
  • Use a state container to keep and share your application state among components (e.g. https://redux.js.org/)
  • Use the new React Context feature. Context provides a way to pass data through the component tree without having to pass props down manually at every level.
like image 57
Arnaud Christ Avatar answered Sep 29 '22 06:09

Arnaud Christ