Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lift state two levels up in react?

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?

like image 414
Ming Jin Avatar asked Nov 23 '17 14:11

Ming Jin


2 Answers

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.

like image 88
rupindr Avatar answered Sep 27 '22 23:09

rupindr


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.

like image 42
Axnyff Avatar answered Sep 27 '22 21:09

Axnyff