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
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
react-navigation has a function withNavigation that populate navigation props in any of your Component. Just use it like that: