Tomasz Kasperek Tomasz Kasperek - 3 years ago 293
React JSX Question

Refreshing children state from parent React

I have a table with some data and each element in the table is a React class component. It looks like this:


All i want is to have one checkbox for "check all" feature (top left checkbox). The thing is I don't know how to solve that because of


I have code like that in single element component:

getInitialState: function() {
return { component: };

render: function() {
var data = this.state.component;
data = data.set('checked','checked'));

And I know I shouldn't get
param from
but it is just temporary.

What I have problem with is: When I update
param in parent it doesn't update state, because
isn't called after refresh (yep, i know it should be like that).

My question is: can I somehow update state of child component? Or it is better way to achieve that.

Answer Source

My approach is that you should have structure something like this in parent's render:

{ {
    <ChildRow props={row.props} />

And then on row.props you have the information whether current row item is checked or not. When parent checkbox is toggled, you populate all the row.props with the status.

On child, you will receive those with componentWillReceiveProps and you do the magic (e.g. set the correct state) when checkbox is toggled:

componentWillReceiveProps: function(props) {
  this.setState({isChecked: props.isChecked});

(Info from the React's docs: Calling this.setState() within this function will not trigger an additional render.)

Child element's render would be something like:

  <input type='checkbox' checked={this.state.isChecked} />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download