Gerard Taub Gerard Taub - 21 days ago 7
React JSX Question

change element in state array does not trigger UI change

I have a

ListView
component in which I need to change the background color of each row independently according to an onPress event.

<View style = {[styles.checkBox, {backgroundColor: this.state.button[rowID]? '#62C6C6':'transparent'}]}/>


Because I don't know how many rows will be rendered, but at most there'll be 4, so I declared an array state
button
as
[false, false, false, false]
and change element value according to the row. For example when I press the first row, with
rowID
is 0, I will set the state of
button
to be
[true, false, false, false]
. In this method, the state for
button
is changed, but the UI does not rerender the background color .
I think the logic here is correct(ish?), is there any way I can get the expected result or there's a smarter way to achieve this

Answer

A suggestion will be to create your own component to render inside each row and only changing the background of that component when clicked. Which then means you don't need to keep an array of the state the state will be in each component itself.

This will be your component:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      backgroundColor:'transparent'
    }
  }

  render() {
    return (
      <View style={{ backgroundColor: this.state.backgroundColor}}>
        <TouchableOpacity onPress={this.changeColor.bind(this)}>
            <Text>This is my Component</Text>
        </TouchableOpacity>
      </View>
    );
  }

  changeColor(){
    this.setState({
      backgroundColor:'#62C6C6'
    });
  }
}

Then in you renderRow you can call your component:

renderRow(rowData){
 return(
  <View>
    <MyComponent/>
  </View>
 )
}