NinetyHH NinetyHH - 1 year ago 141
Javascript Question

React-Native: Back button settings stays on all components

So at the moment I have a small login system. After you are logged in if you press the back button it will ask you if you want to log out and get sent back to login page, the only problem is that if you press back button on the Login page after you logged out, its asking you again if you want to log out, how I add a back button setting for each component?

(I'm using react-native-flux-router for my routes)

componentWillMount() {
BackAndroid.addEventListener('hardwareBackPress', function() {
'Do you want to log out?',
{text: 'Yes', onPress: () => Actions.login({text: 'Logout'})},
{text: 'No'}
return true;

Answer Source

Make the function which handles the back button press in a separate module. If you want to remove the event listener from within logout page itself, handle it in componentWillUnmount as follows:

function componentWillUnmount() {
  BackAndroid.removeEventListener('hardwareBackPress', fn);

If you want to remove the event listener from the login page, import the fn. And handle it in componentWillMount.

import { fn } from '../common/backpress';

function componentWillMount() {
  BackAndroid.removeEventListener('hardwareBackPress', fn);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download