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
JavaScript
x
37
37
1
import React, { Component } from 'react';
2
3
import {
4
StyleSheet,
5
View,
6
Text
7
} from 'react-native';
8
9
import NavButton from '../components/NavButton'
10
11
class HomeScreen extends Component {
12
render() {
13
return (
14
<View style={styles.container}>
15
<Text>
16
Hello World
17
</Text>
18
19
<NavButton
20
navigate={this.props.navigator}
21
/>
22
</View>
23
);
24
}
25
}
26
27
const styles = StyleSheet.create({
28
container: {
29
flex: 1,
30
justifyContent: 'center',
31
alignItems: 'center'
32
}
33
});
34
35
36
export default HomeScreen;
37
Then in the NavButton component I try to navigate to the new screen.
JavaScript
1
14
14
1
class NavButton extends Component {
2
render() {
3
return (
4
<View>
5
<Button
6
title="Go to About"
7
onPress={() => this.props.navigator.navigate('About')}
8
/>
9
</View>
10
);
11
}
12
}
13
export default NavButton;
14
But I keep getting the error “Cannot read property ‘navigate’ of undefined.
Here is my Router.js file as well.
JavaScript
1
16
16
1
import React from 'react';
2
import {StackNavigator} from 'react-navigation';
3
4
import HomeScreen from '../screens/HomeScreen'
5
import AboutScreen from '../screens/AboutScreen'
6
7
8
export const AppNavigator = StackNavigator({
9
Home: {
10
screen: HomeScreen
11
},
12
About: {
13
screen: AboutScreen
14
}
15
})
16
Advertisement
Answer
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
.