I want to add a button(icon) on stack header(on right side). On-click it goes to that page but it's not working. It appears 'undefined is not an object (evaluating 'navigation.navigate')'.
Below is my code:
<Stack.Navigator>
<Stack.Screen name="Page1" component={Page1} />
<Stack.Screen
name="Page2"
component={Page2}
options={{
headerRight: () => (
<View>
<TouchableOpacity
onPress={() => navigation.navigate('Page3')}>
<Image source={require('../assets/image.png')} />
</TouchableOpacity>
</View>
)
}}
/>
<Stack.Screen name="Page4" component={Page4} />
<Stack.Screen name="Page5" component={Page5} />
</Stack.Navigator>
CodePudding user response:
Navigation
is only defined within the screen's components. In your case, you can try useNavigation
hook to navigate to different screen. Import it like:
import { useNavigation } from '@react-navigation/native';
and declare it like:
const navigation = useNavigation();
Then you it to your TouchableOpacity
prop like onPress={() => navigation.navigate('Page3')}
.
Hope this works for you. Thanks
CodePudding user response:
You can pass the navigation from the headerRight:
headerRight: ({navigation}) => (
...
)
or useNavigation():
const navigation = useNavigation();