How do I disable the device back button on Android (react-native)?

8.1k Views Asked by At

How can I disable the physical device back button on Android with React-Native? I don't want to enable it for the user.

3

There are 3 best solutions below

0
On BEST ANSWER

Current open screen is tracked with a listener created when the application is launched, in app.js. Main component of the app creates a BackHandler listener, which responds to the device back button according to the currently open screen.

Main component:

componentDidMount() {
  BackHandler.addEventListener('hardwareBackPress', this.onBackPress);
}

componentWillUnmount() {
  BackHandler.removeEventListener('hardwareBackPress', this.onBackPress);
}

onBackPress = () => {
  if (this.props.currentScreen.name === 'app.main') {
     Alert.alert(
       'Confirm exit',
       'Do you want to exit App?',
       [
         {text: 'CANCEL', style: 'cancel'},
         {text: 'OK', onPress: () => {
           BackHandler.exitApp()
          }
        }
       ]
    );
  } else {
    Navigation.pop(this.props.currentScreen.id);
  }

  return true;
}

App.js

//register to compomentDidApperaListener to keep track on which screen is currently open. The componentName and Id are stored in my redux store
Navigation.events().registerComponentDidAppearListener(({ componentId, componentName }) => {
  store.dispatch(updateCurrentScreen({'name': componentName, 'id': componentId}))
})
1
On

In activity you can override the onBackPressed() and comment the calling to super class.

@Override
public void onBackPressed() {
  // super.onBackPressed(); comment this line to disable back button  press
}
0
On

There is no out of the box support from React Native Navigation as of today on v2. However, you could use BackHandler from React native itself. To handle it and return false to disable it.

Doc on BackHandler

Example

BackHandler.addEventListener('hardwareBackPress', function() {
  return false;
});