How to use BackHandler in react-native-router-flux with tabbar

Im trying to implement Backhandler with Listener, In componentWillMount im adding the listener and in componentWillUnMount im removing the listener but componentWillUnMount is not called when we push to other component. So Listener is there in other Components also, Is there a problem of react-native-router-flux with tabbar

Upvotes: 2

Views: 2721

Answers (1)

Siwananda
Siwananda

Reputation: 106

To make back handler work with a centralised configuration, I'd normally have the handler in a component called AppNavigation which is the parent for Router component.

It looks something like:

<AppNavigation>
  <Router>
      <Scene key="root">
        {/* other scenes */}
      </Scene>
    </Router>
</AppNavigation>

Handling the back button in AppNavigation would then be relatively straightforward:

import React, {Component} from "react";
import {BackAndroid} from "react-native";
import {Actions} from "react-native-router-flux";

class AppNavigation extends Component {

    constructor(props) {
        super(props);
    }

    componentDidMount() {
        //listens to hardwareBackPress
        BackAndroid.addEventListener('hardwareBackPress', () => {
            try {
                Actions.pop();
                return true;
            }
            catch (err) {
                console.debug("Can't pop. Exiting the app...");
                return false;
            }
        });
    }

    componentWillUnmount(){
        console.log("Unmounting app, removing listeners");
        BackAndroid.removeEventListener('hardwareBackPress');
    }

    render() {
        return this.props.children;
    }
}

export default AppNavigation;

P.S. Don't forget to differentiate between android and iOS though, since I believe iOS does not have a back button.

Upvotes: 4

Related Questions