Hardware Backbutton In react native android not working

Viewed 455

I am using react native with navigation. I did not notice but suddenly the back button is not working in the entire app. The header back button on left is working absolutely fine however, the hardware button is not working to go back to the previous screen.

Could anyone suggest anything to solve this?

2 Answers
import the BackHandler from "react-native"
Add in the componentDidMount - >
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);

Implement handleBackButton -> 

handleBackButton(){
    this.props.navigation.popToTop();
    return true;
  }

**popToTop** goes back to the first screen in the stack.

I've been facing the same issue. This issue is related to react-navigation installation steps.

In my case, It was related to react-native-screens library. Sharing the steps below:

react-native-screens package requires one additional configuration step to properly work on Android devices. Edit MainActivity.java file which is located in android/app/src/main/java//MainActivity.java.

Add the following code to the body of MainActivity class:

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(null);
}

and make sure to add an import statement at the top of this file:

import android.os.Bundle;

This change is required to avoid crashes related to View state being not persisted consistently across Activity restarts.

Related