BackHandler override

I’m using expo and react navigation.

I’m trying to overide the android device back button but is seems that the overide is… overided at each navigation !

Let me explain, I’ve handle the BackHandler at the root of my app like this :

import { BackHandler } from 'react-native';

export default App = () => {
  useEffect(() => {
    const backHandlerListener = BackHandler.addEventListener('hardwareBackPress',
      () => {
        console.log('BACK PRESSED FROM APP');
        doSomethingThatIWant();
        return true; // prevent default behaviour;
      }
    );

    return () => {
      backHandlerListener.remove();
    };
  }, []);

  return (
    <div>
       [...MyAppComponents]
    </div>
  )
}

And works fine (understand that I can the log) on the “App page”… But as soon as I navigate to another screen the default behaviour occurs (going back).

I don’t even get the ‘BACK PRESSED FROM APP’ log !

Thus I think that somehow react navigation overides my overide.

I’ve tried to add something like this on a sub-component on another page :

 const backHandlerListener = BackHandler.addEventListener('hardwareBackPress',
  () => {
    console.log('BACK PRESSED FROM THIS COMPONENT');
    return true; // prevent default behaviour;
  }
);

And now pressing the back button works and show the log…

But I can’t imagine to add this eventListener in all my components … !

So is there a way to overide globally (“stronger” than react navigation) the BackHandler ?

  1. SDK Version: 40
  2. Platforms : Android/iOS

Hey @seba99, this has to do with react-navigation more so than Expo. I would recommend reading the docs on handling this and if you feel you’ve discovered a bug, reporting it on the react-navigation repo.

Cheers,
Adam

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.