3

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).

1
  • I've been looking for the same answer for a while now : ( Commented Jan 29, 2022 at 9:04

1 Answer 1

0

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();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.