I'm quite new to React Native, I want to open another screen when a button is tapped, the screen that I want to show is already created. I have used TouchableOpacity
as my button and used navigation on "onPress
" prop. My app is already using Stack navigator and Tab navigator so I have installed those packages.
I have tried but I'm getting an error "undefined is not an object (evaluating 'navigation.navigate')
"
Please help.
In the screen where I'm showing the button:
const myWebview = ({ navigation }) => {
return (
<View style={styles.buttonContainer}>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate("NewListingScreen")}
>
<Text style={{ color: "#ffffff", fontWeight: "bold" }}>
My Button Title
</Text>
</TouchableOpacity>
</View>
);
};
On my Tab Navigator (The screen works fine):
<Tab.Screen
name={routes.newListingScreen}
component={NewListingScreen}
options={({ navigation }) => ({
tabBarButton: () => (
<NewListingButton
onPress={() => {
navigation.navigate(routes.newListingScreen);
dispatch({
type: "SET_NEW_LISTING_SCREEN",
newListingScreen: true,
});
}}
/>
),
tabBarVisible: !user,
})}
/>
When I use const navigation = useNavigation();
CodePudding user response:
My first guess is that the navigation
object itself is undefined
here. Navigation prop is only available on screens. -
const myWebview = ({ navigation }) => {
Using hooks
is a better alternative to passing navigation objects to child components.
import { useNavigation } from '@react-navigation/native';
function NotificationsScreen() {
const navigation = useNavigation();
return(
...
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate('NewListingScreen')}
>
...
);
}