Basic Module Structure
An Android native module consists of:- A module class extending
ReactContextBaseJavaModule - Methods annotated with
@ReactMethod - A
ReactPackageto register the module
Creating Your First Module
import { NativeModules } from 'react-native';
const { CalendarModule } = NativeModules;
// Call the native method
try {
const eventId = await CalendarModule.createEvent(
'Team Meeting',
'Conference Room A'
);
console.log('Created event:', eventId);
} catch (error) {
console.error('Error creating event:', error);
}
Module Methods
Method Annotations
All methods exposed to JavaScript must use the@ReactMethod annotation:
Supported Parameter Types
Native modules automatically convert between JavaScript and Java/Kotlin types:| JavaScript Type | Java/Kotlin Type |
|---|---|
boolean | Boolean |
number | Int, Double, Float |
string | String |
array | ReadableArray |
object | ReadableMap |
function | Callback |
Using Callbacks
Using Promises
Promises provide a cleaner API for async operations:Working with Complex Types
Reading Arrays
Reading Maps
Creating Return Values
Accessing Android Context
TheReactApplicationContext provides access to Android system services:
Constants Export
Expose constants to JavaScript that are available immediately without async calls:Lifecycle Methods
Module Initialization
Module Cleanup
Threading
Running on UI Thread
Example: Image Loader Module
Here’s a real-world example based on React Native’s source code (packages/react-native/ReactAndroid/src/main/java/com/facebook/react/modules/image/ImageLoaderModule.kt:78-118):Best Practices
- Always handle errors and reject promises appropriately
- Use meaningful error codes for promise rejections
- Validate input parameters before processing
- Clean up resources in
invalidate() - Use promises for single async operations
- Document your module’s API
- Consider thread safety when accessing shared resources