React Navigation 3 + Redux + Handle Android Back Button
Handling hardware back button
I was exploring the react navigation library . Latest version of react navigation 3.0 has been released . I have made a sample project with 2 screens.
My Project has 2 screens
a ) Welcome
b) Detail
I have implemented redux by reading the Docs .
I have realised while testing project, hardware back button of android is not working properly. while i am on second screen and pressing hardware back of android and application is closing instead of going back to first screen. Please see the demo
Sample code is given on react navigation site But i was not able to implement in my sample project . I was not able to find any sample project with react navigation 3 + redux + hardware back handler.
I have created a demo project on Github . Any one interested can see the code to check how it will work
Demo of sample project
You can see android hardware back button is working fine now . On second screen(Detail) when i have pressed back button it is sending me to first screen instead of closing the app.
index.js file
ReduxNavigation Component
How it is working
I have created separate component ReduxNavigation
a ) Connect component with redux and send “nav” from mapStateToProps
const mapStateToProps = state => ({ nav: state.nav});
export default connect(mapStateToProps)(ReduxNavigation);
b) Implement BackHandler in component
componentDidMount() { BackHandler.addEventListener("hardwareBackPress", this.onBackPress); } componentWillUnmount() { BackHandler.removeEventListener("hardwareBackPress", this.onBackPress);
} onBackPress = () => {
const { nav, dispatch } = this.props;
if (nav.index === 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
};
onBackPress : Checking if nav.index is 0 it means we do not have any screen in stack and application should close else call NavigationActions.back() to pop current screen.
c) Return App Component with “state” and “dispatch” props
const App = reduxifyNavigator(AppNavigator, "root");
in render method of ReduxNavigation component
render() {
const { nav, dispatch } = this.props;
return <App state={nav} dispatch={dispatch} />;
}
Thanks for reading my article, and clap if you liked it!