Mike jones Mike jones - 3 months ago 24
Javascript Question

How to handle onPress function react

I am using react native with NativeBase components, and I am having a problem calling my _doStuff function. I tried to call

onPress={this._doStuff.bind(this)}


but keep receiving


Cannot read properly 'doStuff' of undefined


_doStuff(){
console.log('Hi');
}

_getList() {
return this.state.listData.map(function(data, i){
return(

<View key={i}>
<ListItem style={styles.listItemContain}>
<Button transparent onPress={this._doStuff.bind(this)}>

<View>
<Thumbnail source={{uri: data.icon}} style={styles.thumbnailStyle}/>
<Text style={styles.title}>{data.name}</Text>
<Text note style={styles.text}>{data.vicinity}</Text>
</View>
</Button>

</ListItem>
</View>

);
});

Answer

this context is lost inside the .map loop. if you are using ES6, try to use fat arrow functions as shown below.

_getList() {
 return this.state.listData.map((data, i) => {
return(

  <View key={i}>
  <ListItem style={styles.listItemContain}>
  <Button transparent onPress={this._doStuff.bind(this)}>

    <View>
    <Thumbnail source={{uri: data.icon}}  style={styles.thumbnailStyle}/>
    <Text style={styles.title}>{data.name}</Text>
    <Text note style={styles.text}>{data.vicinity}</Text>
    </View>
      </Button>

  </ListItem>
  </View>

);
 });

if you cant use ES6 on your project due to various reasons use alternative approach(old school) as shown below...

_getList() {
 return this.state.listData.map(function(data, i){
var that = this;
return(

  <View key={i}>
  <ListItem style={styles.listItemContain}>
  <Button transparent onPress={that._doStuff.bind(that)}>

    <View>
    <Thumbnail source={{uri: data.icon}}  style={styles.thumbnailStyle}/>
    <Text style={styles.title}>{data.name}</Text>
    <Text note style={styles.text}>{data.vicinity}</Text>
    </View>
      </Button>

  </ListItem>
  </View>

);
 });

Comments