3

I need to navigate between two view in React Native. But the problem is my component where the button to navigate is on an other component. I use the react-navigation.

Let me show you :

I have my component MainPage here

class MainPage extends Component {
  render() {
    return <View style={styles.container}>
              <ComponentWithButton /> 
          </View>
  }
}

So in my component ComponentWithButton :

class ComponentWithButton extends Component {
      goToComponent(){
         this.props.navigation.push('Next')
      }
      render() {
        return <View style={styles.container}>
                  <Button onPress={this.goToComponent.bind(this)}/> 
              </View>
      }
    }

My next component is called NextComponent.

I have the error undefined is not an object (evaluating "this.props.navigation.push")

My stack navigator is this :

const RootStack = StackNavigator(
  {
    Main: {
      screen: MainPage
    },
    Next: {
      screen: NextComponent
    }
  },
  {
    initialRouteName: "Main"
  },
  {
    navigationOptions: {
      header: { visible: false }
    }
  }
);

I try to run my code with just one component it's working perfectly. I think there is problem because ComponentWithButton is not called in my RootStack or something like that. I don't know I am a newbie

2 Answers 2

4

you didn't pass the navigation props to the <ComponentWithButton />

do something like this

<ComponentWithButton navigation={this.props.navigation}/>

also the method should be

this.props.navigation.navigate('Next')

if I recall

Sign up to request clarification or add additional context in comments.

2 Comments

@Yapoto if its the right answer please check it so I get the cred
You are too fast, just wait 2min ;)
3

react-navigation has a function withNavigation that populate navigation props in any of your Component. Just use it like that:

import { withNavigation } from 'react-navigation';

class ComponentWithButton extends Component {
      goToComponent(){
         this.props.navigation.push('Next')
      }
      render() {
        return <View style={styles.container}>
                  <Button onPress={this.goToComponent.bind(this)}/> 
              </View>
      }
}

export default withNavigation(ComponentWithButton);

1 Comment

I don’t know but I think so!

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.