I have three screens, Screen A, Screen B and Screen C. If the user press a button in Screen A or Screen B, it will direct them to Screen C. I want Screen C to detect which screen the user came from. How do I achieve that?
CodePudding user response:
Assuming you have navigation stack already installed in your code. If not installed then install react navigation. After that define your navigation stack like below:-
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="AScreen"
component={AScreenComponentName}
options={{headerBackTitleVisible: false, title: 'AScreen',}}
/>
<Stack.Screen
name="BScreen"
component={BScreenComponentName}
options={{headerBackTitleVisible: false, title: 'BScreen',}}
/>
<Stack.Screen
name="CScreen"
component={CScreenComponentName}
options={{headerBackTitleVisible: false, title: 'CScreen',}}
/>
</Stack.Navigator>
</NavigationContainer>
Now if you want to navigate to any screen eg on any button tap then use below code
if using functional component then use below:-
navigation.navigate(Ascreen)
if using class component then use below:-
this.props.navigation.navigate(Ascreen)
CodePudding user response:
You can pass variables by adding an extra option in the navigation function. And get them through the route props. There is a detailed guide in the react-navigation doc.
function Screen1({ navigation }) {
return (
<View>
<Button
onPress={() => {
// extra option in your nativigate function
navigation.navigate('Screen2', {
yourValue: '123',
})
}}
/>
</View>
);
}
function Screen2({ route, navigation }) {
//get the value here
const { yourValue } = route.params;
...
}