Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Handle Android Back Button with React Navigation and Redux

    Spencer CarliSpencer Carli
    react-nativeReact Native

    When handling the navigation state in your own Redux store you make certain trade offs - one of them being the default hardware back button handler. In this lesson you will use BackHandler and Redux to correctly handle hardware back presses.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson




    Instructor: We have our application which has some tab bars. It's got a modal that's being rendered. All the navigation state is being handled through Redux. One ramifications of doing is, is when you press the hardware back button on Android, it closes the application rather than bringing us back to the previous screen.

    To fix that from React navigation, what we'll have to do is import navigation actions. Then from React Native, we'll need to import our back handler. We can then go down to where we're defining our app.

    I'll go ahead and replace our functional component with a typical React component. With that complete, we'll then go ahead and create a new function called onHardwareBack.

    From within this component, we'll say const dispatch and nav = this.props using object destructuring. Then, we'll say if nav.index = 0we'll go ahead and return false. Otherwise, we'll return true.

    Also, if the nav index is not zero, we're going to dispatch a new function. That's going to be NavigationActions.back. What this is saying is if we return true, we're saying that we're handling the hardware back button. If not, then use the system default.

    Before this works, we actually need to call this hardware back function. We'll say within a component in mount, BackHandler.addEventListener. We'll listen to the hardware back press, and when that happens, we'll say this.onHardwareBack.

    We also need to make sure we clean up our event listener, well say onComponentWillUnmount. Again, we'll use the back handler. This time, we'll use remove event listener on the hardware back press. Then, we'll pass this.onHardwareBack.

    Once we refresh the app, and let's say we open up the new modal, press the back button, it will bring us back to our tab bar. If we press back again, it will close the application because our nav index was zero.