Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle or Prevent hardware back button press on react native Modal?

Using react native for android app. Using custom component based on react native modal to present content above an enclosing view.

Already tried to react native Backhandler

   componentDidMount() {
    BackHandler.addEventListener('hardwareBackPress', this.handleBackPress);
  }

  componentWillUnmount() {
    BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress);
  }

  handleBackPress = () => {
    this.goBack(); // works best when the goBack is async
    return true;
  }

or like this

componentDidMount() {
    this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
      this.goBack(); // works best when the goBack is async
      return true;
    });
  }

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

here is open issue

like image 605
Abhishek Garg Avatar asked Oct 22 '18 15:10

Abhishek Garg


People also ask

How do you handle the physical back button in React Native?

To handle the Android Back Button Press in the React Native we have to register the hardwareBackPress event listener with a callback function, which will be called after pressing the Back Button.

Which callback of modal is fired when hardware back button is pressed?

By default, only one handler is fired per hardware back button press. The priority value is used to determine which callback should be called. This is useful because if you have a modal open, you likely would not want the modal to close and the app to navigate backwards when pressing the hardware back button.

How do I add a back button in React Native?

To create a back button with React Router: Set the onClick prop on a button to a function. Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function passing it -1 - navigate(-1) .


1 Answers

Unfortunately, that won't work. If you check the documentation you will see that you need to use the onRequestClose on the modal. BackHandler "...events will not be emitted as long as the modal is open".

Something like this will work:

      <Modal
        visible={visible}
        onRequestClose={() => {
          console.log("back");
        }}
      >
like image 162
Francois Nadeau Avatar answered Jan 04 '23 04:01

Francois Nadeau