'Programmatically trigger Android Back button - React Native

How do you trigger a native Android back button press from inside a React Native button that is handled somewhere else in the application.

For example,

<Pressable onPress={nativeGoBack} />

The event is then handled in another component using the BackHandler API.

BackHandler.addEventListener('hardwareBackPress', () => {
    // Perform action
});

NB: This is not a React Navigation specific question (So navigation.goBack() is not a solution).



Solution 1:[1]

If you want to communicate from react native to adnroid, you should use Native modules.

See documentation https://reactnative.dev/docs/native-modules-android

In short:

  1. Create a native module which handle backbutton from specific activity
class BackPressReactModule(reactContext: ReactApplicationContext?) : ReactContextBaseJavaModule(reactContext) {
    override fun getName(): String {
        return "BackPressReactModule"
    }

    @ReactMethod
    fun goBack() {
        val context = reactApplicationContext
        val currentActivity = context.currentActivity as Activity
        
        currentActivity.onBackPressed()
    }
}
  1. Register BackPressReactModule into your packages in ReactNativeHost. (See documentation)
  2. After successfully exposing module, you can call it from javascript like this:
import {NativeModules} from 'react-native';
const {BackPressReactModule} = NativeModules;

BackPressReactModule.goBack();

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 Michal Biros