I am following the docs trying to handle the Android back button when using react navigation integrated with redux.
Currently pressing the back button exits the entire app wherever you press it. I have tried to handle back press following the guides by adding the handler on the Root component:
const persistConfig = {
key: 'root',
storage,
blacklist: ['nav'],
};
const AppNavigator = createStackNavigator(
{
SelectScreen,
PageScreen,
SettingsScreen,
},
{
initialRouteName: 'SelectScreen',
},
);
const navReducer = createNavigationReducer(AppNavigator);
const appReducer = combineReducers({
nav: navReducer,
theme: themeReducer,
page: pageReducer,
});
const persistedReducer = persistReducer(persistConfig, appReducer);
const middleware = createReactNavigationReduxMiddleware('root', state => state.nav);
const App = reduxifyNavigator(AppNavigator, 'root');
const mapStateToProps = state => ({
state: state.nav,
});
const AppWithNavigationState = connect(mapStateToProps)(App);
const store = createStore(persistedReducer, applyMiddleware(middleware));
const persistor = persistStore(store);
class Root extends React.Component {
componentDidMount() {
BackHandler.addEventListener("hardwareBackPress", this.onBackPress);
}
componentWillUnmount() {
BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
}
onBackPress = () => {
const { dispatch, nav } = this.props;
if (nav.index === 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
};
render() {
return (
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<AppWithNavigationState />
</PersistGate>
</Provider>
);
}
}
AppRegistry.registerComponent(appName, () => Root);
However, I am getting an error because the navigation props doesn't exist in the root component. I know this is probably an error due to my lack of understanding so I'd really appreciate some help on how to get this working!
Thanks