Christopher Reid
Christopher Reid

Reputation: 4482

react-native: re-render rows in ListView on state change

First off, I realize there are a couple similar questions, but none of the answers have helped.

Anyway, I have a simple list view, and when I click on a specific row, I want to add some different styling and content to it.

In _pressRow I set state.selected_row and this re renders the view, in _renderRow it is determined what the selected row is and styling is applied appropriately, but for some reason _renderRow is only called on the initial render, how can I make it update every time, and why is this not happening already?

var List = React.createClass({

  getInitialState: function() {
    var ds = new React.ListView.DataSource({
      rowHasChanged: (r1, r2) => r1 !== r2
    });
    return {
      dataSource: ds.cloneWithRows(some_data),
      loaded: false,
      selected_row: null,
    }     
  },

  _renderRow: function(rowData, sectionID, rowID) {
    var selected = (this.state.selected_row == rowID)
    return (
       <React.View 
          style={selected ? styles.row_expanded : row_styles.row}
          onPress={() => this._pressRow(rowID)>
       </React.View>
    )
  },

  _pressRow: function(rowId){
    this.setState({
      selected_row: rowId,
    });
  },

  render: function() {

      return <React.View>
        <React.ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          style={styles.container}
        />
      </React.View>

  }

});

Upvotes: 0

Views: 1132

Answers (1)

Christopher Reid
Christopher Reid

Reputation: 4482

I got it working by pasting a few different answers together...

  _pressRow: function(rowId){

    var clone = this.state.tours.map((item, i) => {
      return {
        ...item,
        selected: i == rowId ? true : false
      }
    });

    this.setState({
      data: clone,
      selected_row: rowId,
      dataSource: this.state.dataSource.cloneWithRows(clone)
    });

  },

You have to explicitly create new objects based on the old data. Simply changing properties doesn't work for some reason.

Upvotes: 2

Related Questions