Writing a Legacy Native Module in Kotlin
Create a ReactContextBaseJavaModule in Kotlin, annotate a method with @ReactMethod, expose it through a ReactPackage, and call it from JavaScript.
What Is a Legacy Native Module
A legacy native module allows you to call native Android (Kotlin/Java) code from JavaScript in a React Native app. When the built-in React Native APIs do not cover a device feature you need, you write a native module to bridge the gap. Legacy modules use the Bridge architecture, which means calls go asynchronously across the JS-to-native bridge.
Creating the Kotlin Module Class
Every Android native module extends ReactContextBaseJavaModule. You override getName() to return the name that JavaScript will use to call your module. Place this class inside the android/app/src/main/java/com/yourapp/ folder alongside existing Android source files.
// ToastModule.kt
package com.yourapp
import android.widget.Toast
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
class ToastModule(reactContext: ReactApplicationContext) :
ReactContextBaseJavaModule(reactContext) {
override fun getName(): String = 'ToastModule'
}All lessons in this course
- Writing a Legacy Native Module in Kotlin
- Writing a Legacy Native Module in Swift
- Turbo Native Modules with JSI
- Async Callbacks, Promises, and Events from Native