Reputation: 215
I made a little helper component
const NavHelper = ({ navigation, dest }) => {
return (
<TouchableOpacity onPress={() => navigation.navigate(`${dest}`)}>
<Text>Go to {dest}</Text>
</TouchableOpacity>
);
};
It works by sending navigation as a prop.
<NavHelper navigation={navigation} dest="List" />
But since this component will always use navigation it would be nice if I could access navigation without having to send it as a prop to avoid repetition.
https://reactnavigation.org/docs/connecting-navigation-prop/
On the homepage it says you can do this by by using
import { useNavigation } from '@react-navigation/native';
const NavHelper = ({ dest }) => {
const navigation = useNavigation();
return (
<TouchableOpacity onPress={() => navigation.navigate(`${dest}`)}>
<Text>Go to {dest} Demo</Text>
</TouchableOpacity>
);
};
But when I try this approach in my component, the emulator says it can't find a navigator object. What am I missing?
Upvotes: 2
Views: 1106
Reputation: 215
Easy solution, turns out there are multiple versions of react-navigation and I was looking at the documentation for 5.x while using 4.x.
I was supposed to use https://reactnavigation.org/docs/4.x/connecting-navigation-prop
Upvotes: 1