NinetyHH NinetyHH - 2 months ago 69
React JSX Question

React-Native: Go back on android hardware back button pressed

I am trying to add going back on webview when the android backbutton was pressed and I still couldn't manage to make it work.

This is my code:

<WebView
ref={WEBVIEW_REF}
source={source}
domStorageEnabled={true}
onNavigationStateChange={this.onNavigationStateChange}
/>

componentDidMount() {
BackAndroid.addEventListener('hardwareBackPress', function() {
if(this.state.backButtonEnabled) {
this.refs[WEBVIEW_REF].goBack();
return true;
}
});
};

onNavigationStateChange = (navState) => {
this.setState({
backButtonEnabled: navState.canGoBack,
});
};


With the code above I'm getting the error undefined is not an object this.state.backButtonEnabled (which is set in the state).

Than I just wanted to see if the goBack works so I removed the if statement and than I was getting the error undefined is not an object this.refs[WEBVIEW_REF].

What is the best solution for this?

Answer
class MyComponent extends Component {
    state = {};
    componentDidMount(){
         BackAndroid.addEventListener('hardwareBackPress', this.backHandler);
    }
    componentWillUnmount(){
         BackAndroid.removeEventListener('hardwareBackPress', this.backHandler);
    }
    backHandler = () => {
        if(this.state.backButtonEnabled) {
            this.refs[WEBVIEW_REF].goBack();
            return true;
        }
    }
}

1) Bind your handler 2) You should removeListener on unmount.