How can I disable the physical device back button on Android with React-Native? I don't want to enable it for the user.
Asked
Active
Viewed 7,835 times
3 Answers
5
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;
});
1
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
}

Velu Loganathan
- 241
- 2
- 11
-
Sorry, seems like I didn't clearly specify that this was for react-native, and I am using a library called react-native-navigation for navigation – Oskar Gusgård Dec 13 '18 at 15:33
1
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}))
})

Oskar Gusgård
- 457
- 7
- 20