frazer87 frazer87 -4 years ago 46
React JSX Question

React Navigation onPress in own function

I've implemented the React Navigation example as in the tutorial https://reactnavigation.org/docs/intro/ and it works fine.

<Button
onPress={() => navigate('Chat')}
title="Chat with Lucy"
/>


Instead of calling navigate direct in onPress, I want to call it in a separate function btnToChat. I've tried to call it with this.props.navigation.navigate, but it doesn't work. Do you have any suggestions? Thank you!

btnToChat(){
console.log("test");
this.props.navigation.navigate('Chat');
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Button
onPress={this._btnToChat}
/>
</View>
);
}
}


The following error appears: undefined is not an object (evaluating this.props.navigation)

Answer Source

Everything is proper, you just need to bind the _btnToChat method to access (correct context) this keyword inside that.

Like this:

btnToChat = () => {                      //here use arrow  function
    console.log("test");
    this.props.navigation.navigate('Chat');    
}

render() {
    const { navigate } = this.props.navigation;
    return (
        <View>
            <Button
                onPress={this._btnToChat}
            />  
        </View>
    );
}

Or define the binding of _btnToChat method inside constructor:

constructor(){
   super();
   this._btnToChat = this._btnToChat.bind(this);
}

btnToChat (){           
    console.log("test");
    this.props.navigation.navigate('Chat');    
}

render() {
    const { navigate } = this.props.navigation;
    return (
        <View>
            <Button
                onPress={this._btnToChat}
            />  
        </View>
    );
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download