Robin_f Robin_f - 1 month ago 6
React JSX Question

Letting a child know that it should update its state in React

I'm trying to let a child Component know that it should update its state after a prop change in the parent.

There is no state that needs to be shared between the two. The only thing that needs to happen is that the parent should somehow let the child know that it needs to update its state (literally call

setState
by itself with the info it already has).

So far I can only figure out to do in the "React"-way through the
componentWillReceiveProps
and sending some arbitrary props, like a number, to let the child know that it should call the function to set the state.

Another way would be to use signals to let the child know, but this seems a bit over the top for this situation.

So in summary:


  • The parent needs to let the child know that it should call a function

  • The function will update the state (
    setState
    ) of the child

  • There is no need for the child to receive any information from the parent



Can anyone help me figure out the best way to do this?

As you can see in the snippet, this is more or less the situation. I would like to know the best way to have the Child component call the
_updateState
function when the Parents props have changed (does not happen in the snippet right now).



//Imagine this is the redux-container that passes the store state to the parent.
class ParentWrapper extends React.Component {
constructor(){
super();

this.state = {status: 'normal'};
}

//This would be an action to the reducer that would update the store state
_updateStatus(){
this.setState({status: 'updated'});
}

render(){
return (
<div>
<button onClick={this._updateStatus.bind(this)}>Click me</button>

<Parent status={this.state.status} />
</div>
);
}
}

class Parent extends React.Component {
render(){
return (
<div>
<Child />
</div>
);
}
}

Parent.propTypes = {
status: React.PropTypes.string
};

Parent.defaultProps = {
status: 'normal'
};

class Child extends React.Component {
constructor(){
super();

this.state = { test: 1 };
}

_updateState(){
this.setState({test: this.state.test + 1});
}

render(){
return (
<div>Child: {this.state.test}</div>
);
}
}

ReactDOM.render(<ParentWrapper />, document.getElementById('container'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>

<div id="container"></div>





EDIT: added snippet.

Answer

You can use refs to access all the methods under the child component.

See the following fiddle

https://jsfiddle.net/pranesh_ravi/412j5ucw/

Here using refs, I'm calling a function inside the child which will change the state of the child component.

Comments