me_astr
me_astr

Reputation: 1042

ignite 2.0: Android back button closing app react-navigation

I am using default ignite 2.0 boilerplate code. Suppose I open a new screen using this.props.navigation.navigate('SecondScreen')

After opening the 'SecondScreen' if I am pressing android hardware back button it is closing app. 'SecondScreen' ui back button at top of screen is working fine.

App navigation code:

const PrimaryNav = StackNavigator({
  Home: { screen: Home },
  SecondScreen: { screen: SecondScreen }
}, {
    // Default config for all screens
    initialRouteName: 'Home',
    navigationOptions: {
      headerStyle: styles.header
    }
})

Upvotes: 2

Views: 752

Answers (2)

robertherber
robertherber

Reputation: 852

I'm guessing you're using Redux integration, which means you'll need to handle the back button yourself as pointed out here. Also check out the reference for Backhandler.

What I've done is implement it like this:

import { BackHandler } from 'react-native';
import { NavigationActions } from 'react-navigation';

/* subscribe this to the redux store, should look something like this subscriber(store.dispatch, store.getState); */
export const subscriber = (dispatch, getState) => {
  BackHandler.addEventListener('hardwareBackPress', () => {
    const appShouldExit = true || false; //depending on which screen you're at
    if (appShouldExit) {
      BackHandler.exitApp();
    }
        
    const backAction = NavigationActions.back();
    dispatch(backAction);
    
    return true;
  });
});

Upvotes: 2

me_astr
me_astr

Reputation: 1042

In my component I added this code and it is working fine now.

  import { BackHandler } from 'react-native'

  componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.props.navigation.goBack);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.props.navigation.goBack);
  }

Upvotes: 0

Related Questions