React native navigation from stack navigator is not being passed down to the Restaurantsscreen function
This is the function which has to use naviagtion but it cant
export const RestaurantsScreen = ({navigation}) => (
<SafeArea>
<View style={{"backgroundColor": "rgba(255, 255, 255, 255)"}}>
<FlatList
data={[
{ name: 1 }
]}
renderItem={(item) =>{return (
<Pressable onPress={ ()=>console.log(navigation)}>
<RestaurantInfoCard />
</Pressable>
);
}}
and these are the functions where stack navigator is defined
function App() {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={Screentwo} /> // this screen is currently loaded and the screentwo is importing the Restaurants screen function inside it as a component
</Stack.Navigator>
</NavigationContainer>
);
}
Kindly help thanks
CodePudding user response:
You have two solutions :
- Past the
navigation
props from theScreentwo
to you're child componentRestaurantsScreen
- Used the
useNavigation
hooks directly in yourRestaurantsScreen
component (see link for this hook : https://reactnavigation.org/docs/use-navigation/)
Example of the first solution:
//Screentwo inherit navigation props direclty, as this component is called in your Stack.Navigator
export const Screentwo = ({navigation}) => {
return(
//As RestaurantsScreen is not called directly in your Stack.Navigator,
//this component will not inherit navigation props,
//you need to past manually navigation props from Screentwo in this way
<RestaurantsScreen navigation={navigation} />
)
}
Example of the second solution with useNavigation
:
//Directly in your RestaurantsScreen component
import { useNavigation } from '@react-navigation/native';
//No need to import navigation props
export const RestaurantsScreen = () => {
//Call useNavigation, and navigation can be used in the exact same way as if you past it as a props
const navigation = useNavigation()
return (
<SafeArea>
the rest of your code here
</SafeArea>
)
}