I'm trying to work with the react-native and react-navigation library. I'm trying to pass a param to multiple screens sharing the same Tab Navigator.
This is the scenery:
App.js
const MainScreen = ({ navigation }) => {
return (
<Button
onPress={() =>
navigation.navigate("User", { prop_i_want_to_share: "asd" })
} //This is the param I would like to share
/>
);
};
const UserInfoScreen = ({ route }) => (
<View>
{route.params.prop_i_want_to_share} // Here I would like to get the param used in navigation
</View>
);
const UserEditScreen = ({ route }) => (
<View>
{route.params.prop_i_want_to_share} // Here I would like to get the param used in navigation
</View>
);
const UserTab = () => (
<Tab.Navigator>
<Stack.Screen name="UserInfo" component={UserInfoScreen} />
<Stack.Screen name="UserEdit" component={UserEditScreen} />
</Tab.Navigator>
);
render() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Main" component={MainScreen} />
<Stack.Screen name="User" component={UserTab} />
</Stack.Navigator>
</NavigationContainer>
);
}
Basically, I'm trying to propagate the params, but I think I didn't design properly the navigator structure and that's why I'm finding this issue. What would you change to make this possible?
CodePudding user response:
I have not tried it yet, but with latest v6, you can use Groups:
<Stack.Navigator>
<Stack.Group screenOptions={({ route, navigation }) => ({ prop_i_want_to_share: 'asd' })}>
{/* screens */}
</Stack.Group>
</Stack.Navigator>
CodePudding user response:
See the answer for this related question.
Depending on what version of react-navigation you're using (I'll assume 6.x), to pass to a nested navigator you could use:
In MainScreen
navigation.navigate('User', {
screen: 'UserInfo',
params: { prop_i_want_to_share: "asd" },
});
Then you can pass the param to the next screen once you navigate to it:
In UserInfoScreen
navigation.navigate('User', {
screen: 'UserEdit',
params: { prop_i_want_to_share: route.params.prop_i_want_to_share },
});
But if you're trying to update a global variable, that is a variable that gets used in multiple screens (ex: CurrentlyLoggedInUserId), you might not want to use params at all. You could use a state management tool like Recoil, Redux, React's useContext or even create your own custom hook.