Pass data onClick event to the function in loop

I create my component in the parent component this way:

renderRow(row){
  var Buttons = new Array(this.props.w)
  for (var i = 0; i < this.props.w; i++) {
    var thisButton=<FieldButton handler={this.actionFunction} key={'row'+ row +'col'+ i}></FieldButton>
    Buttons.push(thisButton)
  }
  return Buttons
}

renderField(){
  var Field = new Array(this.props.h);
  for (var i = 0; i < this.props.h; i++) {
    var row = this.renderRow(i);
    Field.push(<View key={i} style={styles.fieldWrap}>{row}</View>);
  }
  this.setState({field: Field})
}

The Goal:

I have to change the state of the FieldButton component.

My question:

What is the right way to change the Childs component state?

First Attempt:

I tried to bind a prop to the state of the parent component:

 <FieldButton color={this.state.color} handler={this.actionFunction} key={'row'+ row +'col'+ i}></FieldButton>

I also implemented the componentWillReceiveProps Method but it was never called.

I tried to move the child outside of the for loop and it worked.

Second Attempt:

I tried to use refs: this question.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

The problem in your case, seems to be caused due to closure. You should make use of let for the for loop, otherwise everytime forLoop will call this.renderRow(i) with the this.props.h.length - 1 and similary in your renderRow case as well

renderRow(row){
  var Buttons = new Array(this.props.w)
  for (let i = 0; i < this.props.w; i++) {
    let thisButton=<FieldButton handler={this.actionFunction} key={'row'+ row +'col'+ i}></FieldButton>
    Buttons.push(thisButton)
  }
  return Buttons
}

renderField(){
  var Field = new Array(this.props.h);
  for (let i = 0; i < this.props.h; i++) {
    let row = this.renderRow(i);
    Field.push(<View key={i} style={styles.fieldWrap}>{row}</View>);
  }
  this.setState({field: Field})
}

After this since, your Parent component already holds the state, you could pass it as props and then implement componentWillReceiveProps.

P.S. However if your child component state is directly derivable from
props, you should directly use the props instead of keeping a local
state in child

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply