'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



Solution 1:[1]

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");
        }}
      >

Solution 2:[2]

it works for me

<Modal isVisible={ProfileImageEditModal}
        onRequestClose={() => {
           setProfileImageEditModal(false)
          }}
/>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Menon Hasan