3

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)

1 Answer 1

4

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>
    );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.