Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - Device back button handling

I want to check if there are more than one screens are on stack when device back button is hit. If yes, I want to show previous screen and if no, I want to exit app.

I have checked number of examples but those use BackAndroid and Navigator. But both of them are deprecated. BackHandler is replacement for BackAndroid. And I can show previous screen by using props.navigation.goBack(null).

But I am unable to find code for finding screen count in stack. I don't want to use deprecated Navigator!

like image 624
Virat18 Avatar asked Jul 11 '17 09:07

Virat18


People also ask

How do you handle the mobile Back button in react native?

To handle the Android Back Button Press in the React Native we have to register the hardwareBackPress event listener with a callback function, which will be called after pressing the Back Button.

How do you handle the back button react?

To go back to the previous page, pass -1 as a parameter to the navigate() function, e.g. navigate(-1) . Calling navigate with -1 is the same as hitting the back button in the browser. Similarly, you can call the navigate function with -2 to go 2 pages back.

Which callback of modal is fired when hardware back button is pressed react native?

The Backhandler API detects hardware button presses for back navigation, lets you register event listeners for the system's back action, and lets you control how your application responds.

How do you go back in react native?

The header bar will automatically show a back button, but you can programmatically go back by calling navigation. goBack() . On Android, the hardware back button just works as expected.


1 Answers

This example will show you back navigation which is expected generally in most of the flows. You will have to add following code to every screen depending on expected behavior. There are 2 cases: 1. If there are more than 1 screen on stack, device back button will show previous screen. 2. If there is only 1 screen on stack, device back button will exit app.

Case 1: Show previous screen

import { BackHandler } from 'react-native';  constructor(props) {     super(props)     this.handleBackButtonClick = this.handleBackButtonClick.bind(this); }  componentWillMount() {     BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick); }  componentWillUnmount() {     BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick); }  handleBackButtonClick() {     this.props.navigation.goBack(null);     return true; } 

Important: Don't forget to bind method in constructor and to remove listener in componentWillUnmount.

Case 2: Exit App

In this case, no need to handle anything on that screen where you want to exit app.

Important: This should be only screen on stack.

like image 183
Virat18 Avatar answered Sep 22 '22 11:09

Virat18