Reputation: 451
I have components as shown below
Component1 --- Component3
|
Component2
|
Component4
Components 2 and 3 are children of 1, and Component 4 is the child of 2. I need to pass data from Component4 which I am storing as its state to Component3 which will display it. I presume the way to do this is to pass the state to from Component4 up to Component2 which will further send the state to Component1 using callbacks and finally Component1 will pass the state down to Component3. Is this the best way to do this?
Upvotes: 0
Views: 107
Reputation: 2139
Best and scalable solution for this problem is using Flux or Redux which helps in the bidirectional data flow. They have a store where the data is stored, and whenever we want we can access and modify the data which is available to all components.
Have a look onto Redux and you can find examples implemented using Redux here
Upvotes: 1
Reputation: 2339
Store the data in the state highest common parent (Component 1). Create methods on component1 that manipulate this state and bind this to them in the constructor. Then pass the state down to component3.
class component1 extends React.Component {
constuctor(props) {
super(props);
this.stateChanger = this.stateChanger.bind(this)
this.state = {
foo: 'bar'
}
}
stateChanger(e) {
this.setState({ foo: 'baz' })
}
render() {
<Component3 foo={this.state.foo} />
<Component2 stateChanger={this.stateChanger} />
}
}
edit: pass the stateChanger function down to component4 like below:
class Component2 extends React.Component {
render() {
return (
<div>
<Component4 stateChanger={this.props.stateChanger} />
</div>
)
}
}
Then do what you will with it. Here is an article you should check out!
Upvotes: 2
Reputation: 15914
Callbacks will work. Another common solution is to lift the state up.
Instead of storing the state in Component4, simply move the state to Component1 and pass them down as props to Component3 and 4.
Personally I don't like a long callback chain, lifting the state is usually feels better to me.
If you have a lot of state that need to be shared between components, you should start to consider a state management solution, like Redux or MobX etc.
Upvotes: 2