In react-navigation, know there is a way to perform custom actions when the back button is pressed. Is there a similar way to do this when the user swipes to go back to the last screen?
By default React Navigation will handle the Android back button for you, however we'll need to override the defaults. If you're at the top of the stack and press the android back button the application will close. If you've navigated within the stack anywhere then the screen will pop.
The most common form of back navigation is done through the back button. The stack layout contains a back button by default, also known as the software back button. RNN handles the back navigation for you, but there are use cases where you might need to override the default behavior of the back navigation.
Use the goBack() Method to Go Back One Screen in React Native. The goBack() method is one of the most important methods in the react-navigation library. It allows you to go back to one of the previous screens in your navigation stack.
React Navigation 5.7 introduced a simple way to do this without the need to override back actions or swipe gestures, basically you intercept the back action in the component and execute a callback before it happens:
import {useNavigation} from '@react-navigation/native';
const MyScreenComponent = (props) => {
const navigation = useNavigation();
React.useEffect(() => (
navigation.addListener('beforeRemove', (e) => {
// Prevent default behavior of leaving the screen (if needed)
e.preventDefault();
// Do whatever...
})
), [navigation]);
// Rest of component
}
In this example I'm using the useNavigation
hook to access the navigation
object, but you can also extract it from the props, it really depends on how your app is built.
Official documentation.
I was able to determine whether the app is going back via the back button or swiping back with the getStateForAction function of the router. Play around with checking the action and state variables to fine tune it more if needed.
export const ScreensStack = StackNavigator(
{
Login: {screen: LoginScreen},
Schedule: {screen: ScheduleScreen},
}
/**
* Intercept actions occuring in the screen stack.
*/
const getStateForActionScreensStack = ScreensStack.router.getStateForAction;
ScreensStack.router = {
...ScreensStack.router,
getStateForAction(action, state) {
if (action.type == 'Navigation/BACK') {
console.log('We are going back...');
}
return getStateForActionScreensStack(action, state);
},
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With