How to handle device back button in react-native with react-native-router-flex

Using react native device back API:

Here we discuss “How to handle device back button in react-native with react-native-router-flex“, in iOS there is no back button so no need to handle this but in android device back button is a big issue, for handling the device back button react-native provide a API.

I’m a big fan of React Native, because it is very easy to implement complicated concepts and designs, in below example i am going to explain you in detail how to handle device back button.

Output is like –

How to handle device back button in react-native with react-native-router-flex

so let’s see how we handle this.

Follow these steps for handling android back button in react native-

Step 1: 

import the following line.

import { BackHandler } from ‘react-native’;

Step 2: 

Declare it on constructor so we find it only one time.

constructor(props) {
 super(props)
 this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}

Step 3: 

Now we call it on ComponentDidMount().

componentWillMount() {
 BackHandler.addEventListener(‘hardwareBackPress’, 
 this.handleBackButtonClick);
}

Step 4: 

When we leave that page then we need to unsubscribe the API, so we put that code within unmount lifecycle of react native.

componentWillUnmount() {
    BackHandler.removeEventListener(‘hardwareBackPress’, 
   this.handleBackButtonClick);
}

Step 5:

 Now we define the function.

handleBackButtonClick() {
 Actions.sceneName();//such as: home(),login() etc
}

I’m a big fan of React Native, because it is very easy to implement complicated concepts and designs, in above example, explain you in detail how to handle device back in a very simple way.

So we completed the topic “How to handle device back button in react-native with react-native-router-flex“.

You can find my post on medium as well click here please follow me on medium as well.

You can find my next post here.

If have any query/issue, please feel free to ask.

Happy Coding Guys.

Related Post

5 Replies to “How to handle device back button in react-native with react-native-router-flex”

  1. back handler add in step 5, follow step 5 in this blog if it not solved then add a screenshot of your project

  2. App.js in my home screen is import .. “bottom tab bar” .
    name is = tabnavigator
    where you code add back handler .

Leave a Reply

Your email address will not be published. Required fields are marked *