I am trying to get previous route name to my current screen. Because based on the previous screen name, I have to show/hide few objects in current screen.
To get previous screen name, I have tried following
JavaScript
x
7
1
componentDidMount() {
2
const { navigation } = this.props;
3
if (navigation.state.params && navigation.state.params.previous_screen) {
4
console.log('navigation.state.params.previous_screen', navigation.state.params.previous_screen);
5
}
6
}
7
But, It’s getting undefined
in console log.
Any suggestions?
Advertisement
Answer
You need to use NavigationActions
JavaScript
1
14
14
1
goToScreen = () => {
2
3
const navigateAction = NavigationActions.navigate({
4
routeName: 'Profile',
5
6
params: { previous_screen: 'Home' }, // current screen
7
8
action: NavigationActions.navigate({ routeName: 'Profile' }), // screen you want to navigate to
9
});
10
11
this.props.navigation.dispatch(navigateAction);
12
13
};
14
call the above function in your onPress
JavaScript
1
2
1
<Text onPress={this.goToScreen}>Go to screen</Text>
2
In your other screen
JavaScript
1
14
14
1
componentDidMount = () => {
2
3
const { navigation } = this.props;
4
if (navigation.state.params && navigation.state.params.previous_screen) {
5
6
this.setState({
7
previous_screen: navigation.state.params.previous_screen
8
});
9
10
} else {
11
console.log("ERROR");
12
}
13
};
14
Function version
JavaScript
1
7
1
const goToScreen = () => {
2
// assuming that navigation is passed in props
3
props.navigation.navigate('Settings', {
4
previous_screen: 'Home'
5
})
6
}
7
And access the params like
JavaScript
1
6
1
const Settings = ({ route }) => {
2
const { previous_screen } = route.params;
3
4
return .
5
}
6