Following this example by React.
I want to be able to lift states two levels up. Meaning, when an event occurs at the lower level component, I want it to affect the state two levels up. How should I do this? Is this even recommended?
For example, Component A is the parent of Component B, Component B is the parent of Component C. A -> B -> C.
In A,
handleChange = (e) => {console.log(e)}
<B onChange={handleChange}/>
In B,
handleChange = (e) => this.props.onChange(e)
<C onChange={this.handleChange}/>
In C,
handleChange = (e) => this.props.onChange(e)
<button onClick={this.handleChange}></button>
Is there a better way to do this?
Using your example A->B->C here. You should create a setter in A.
state of A:
this.state={ stateA: "whatever"}
function in A:
setStateA(newVal){
this.setState({stateA: newVal});
}
Now pass it as property to B
<B setStateA={this.setStateA} />
In B:
<C setStateA={this.props.setStateA} />
In C:
// some code
this.props.setStateA("a new value");
//some code
I think this is the best way to do it. Passing function as property to children. Hope it helps.
You don't need to recreate the function in the B component, simply passing it along will work.
B will simply look like
<C onChange={this.props.onChange}/>
Same for C where you can directly attach the event the props to onClick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With