I've been trying to get up and running with react navigation but I run into a problem when I try to move navigation items into their own components.
HomeScreen.js
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text
} from 'react-native';
import NavButton from '../components/NavButton'
class HomeScreen extends Component {
render() {
return (
<View style={styles.container}>
<Text>
Hello World
</Text>
<NavButton
navigate={this.props.navigator}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
export default HomeScreen;
Then in the NavButton component I try to navigate to the new screen.
class NavButton extends Component {
render() {
return (
<View>
<Button
title="Go to About"
onPress={() => this.props.navigator.navigate('About')}
/>
</View>
);
}
}
export default NavButton;
But I keep getting the error "Cannot read property 'navigate' of undefined.
Here is my Router.js file as well.
import React from 'react';
import {StackNavigator} from 'react-navigation';
import HomeScreen from '../screens/HomeScreen'
import AboutScreen from '../screens/AboutScreen'
export const AppNavigator = StackNavigator({
Home: {
screen: HomeScreen
},
About: {
screen: AboutScreen
}
})
If you rename navigate={this.props.navigator}
to navigator={this.props.navigation}
, it should work because in NavButton you are calling this.props.navigator.navigate
.
import * as React from 'react';
import { Button } from 'react-native';
import { useNavigation } from '@react-navigation/native';
function GoToButton() {
const navigation = useNavigation();
return (
<Button
title='Screen Name'
onPress={() => navigation.navigate(screenName)}
/>
);
}
You can use useNavigation from @react-navigation/native with React Navigation v 5.x. More details in the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With