1
votes

I want to handle the back button in my React Native application. I know that can use addEventListener in componentdidmount and componentWillUnmount to handle the back button.

My problem is, the page still exists in stack navigation, so on the other page I have the EventListener, but I want the EventListener on only one page.

The following example code from How to exit React Native app on back button pressed does not solve the problem.

3
Please show an example of the problematic code - James
Formatted text and syntax. - Trenton McKinney
why edit and revive when this question is from 1 year ago and likely abandoned. - Someone Special

3 Answers

0
votes

You can use react-navigation's withNavigationFocus HOC.

Using it you know inside your screen if it's the focussed one or not. An example of an implementation would be:

componentDidMount = () => {
    this.backHandler = BackHandler.addEventListener('hardwareBackPress', this.handleBackPress)
}

componentDidUpdate = (prevProps) => {
    if (prevProps.isFocused !== this.props.isFocused) {
        this.props.isFocused ?
        this.backHandler = BackHandler.addEventListener('hardwareBackPress', this.handleBackPress):
        this.backHandler.remove()
    }
}

componentWillUnmount() {
    this.backHandler.remove()
}

Don't forget to import withNavigationFocus and BackHandler:

import { withNavigationFocus } from "react-navigation";
import { BackHandler } from "react-native";

The in your export you have to do:

export default withNavigationFocus(*componentName*)
0
votes

In your app navigator

function onBackPress() {
  if (Actions.state.index === 0) {
    return false;
  }
  Actions.pop();
  return true;
}



const AppNavigator = conn()(Router);

  return (
    <AppNavigator navigator={navigator} backAndroidHandler={onBackPress} />
  );
0
votes

Try to use this solution.

It's easy as to wrap your component that is on the screen now with:

import { AndroidBackHandler } from 'react-navigation-backhandler';
<AndroidBackHandler onBackPress={this.onBackButtonPressAndroid}>
    <SomeComponent />
</AndroidBackHandler>