vikrantnegi
vikrantnegi

Reputation: 2472

Exit app when clicked back on home screen

I'm using react-native-router-flux for react-native navigation. I've 4 scene stack on my react-native app.

When the app first boots up on Home screen, clicking on back button exits the app as expected.

But when I navigate to any other screen and comes back to the home screen, the back button doesn't seem to work anymore.

Here is the code snippet:

onBackPress() {    
    if (Actions.state.index === 0) {
      return false;
    }
    Actions.pop();
    return true;
}

<Router backAndroidHandler={this.onBackPress}>
    <Scene key="root">
        <Scene key="home" initial component={HomeScreen} />    
        <Scene key="screen2" component={MainScreen} />    
        <Scene key="screen3" component={ScreenSec} />
    </Scene>
</Router>

I navigate to the home screen by using Actions.pop(); in my components.

Any idea on how can I exit the app whenever I come back to home screen by navigation to other screens?

Thanks.

Upvotes: 4

Views: 2247

Answers (1)

GenericJam
GenericJam

Reputation: 3015

If you implement the reducer from the Example project that is a part of this library, you can tap into the behavior from within the reducer.

const reducerCreate = params => {

  const defaultReducer = new Reducer(params);

  return (state, action) => {
    // Open this up in your console of choice and dive into this action variable
    console.log('ACTION:', action);
    // Add some lines like this to grab the action you want
    if(action.type === 'Navigation/BACK' && state.index === 0){
      BackHandler.exitApp()
    }
    return defaultReducer(state, action);
  };
};

And make sure the reducer is tied into the Router

<Router
  createReducer={reducerCreate}
  backAndroidHandler={this.onBackPress}
>

This isn't ideal and is just here as a workaround until the bug is fixed in the library so if you read this answer in the future, check to make sure you really need to use this workaround.

Upvotes: 3

Related Questions