Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactNative - Tapping row in ListView gives error: Cannot read property `_pressRow` of null

I am building a small ReactNative + Redux app using a ListView. I was following the example code from the docs and came up with the following setup. My current implementation is very close to the sample code, but for some reason, I am getting an error when I want to "click" a list item.

Here are the relevant parts from my code:

JobsRootComponent.js

class JobsRootComponent extends Component {

  ...

  _pressRow(row) {
      console.log('JobsRootComponent - _pressRow ', row)
  }

  ...

  _renderRow(rowData, section, row) {
      const title = rowData.title
      const subtitle = 'by ' + rowData.by
      return (
         <TouchableHighlight onPress={() => this._pressRow(row)}>
           <View style={styles.cellContainer}>
             <Text style={styles.cellTitle}>{title}</Text>
             <Text style={styles.cellSubtitle}>{subtitle}</Text>
           </View>
         </TouchableHighlight>          
      )
  }

  ...

  render() {
    return (
        <ListView
          style={styles.container}
          dataSource={this.props.dataSource}
          renderRow={this._renderRow}
        />
      )
  }

  ...

}

This code looks fine to me, but for some reason, when clicking a list item, javacript crashes and displays the following two errors in the chrome dev console:

  1. Cannot read property _pressRow of null
  2. Unhandled JS Exception: Cannot read property _pressRow of null

According to my understanding, this means that the object whose _pressRow property was targeted with the click is actually null. But shouldn't that object be my JobsRootComponent? How come it can be null at this point?

like image 676
nburk Avatar asked Mar 30 '16 08:03

nburk


1 Answers

After searching for a while, I came across this tutorial describing how to implement a simple ToDo-app which helped me solve the issue myself.

The problem was due to the way I assigned _renderRow to the renderRow-property of the ListView: Instead of simply doing renderRow={this._renderRow}, I needed to use javascript's bind() function:renderRow={this._renderRow.bind(this).

For reference, here is what my render() method now looks like:

render() {
  return (
      <ListView
        style={styles.container}
        dataSource={this.props.dataSource}
        renderRow={this._renderRow.bind(this)}
      />
    )
}
like image 64
nburk Avatar answered Nov 15 '22 14:11

nburk