Lesson 7 of 10
Writing Native Modules (RN CLI)
When no existing library covers your need, you write a native module. With the New Architecture, this means using Codegen: define a TypeScript spec, Codegen generates the C++ glue code, and you implement the native side in Kotlin and Swift.
New Architecture Native Module (Turbo Module)
// 1. TypeScript spec - Codegen reads this to generate C++ bindings
// NativeCalculator.ts (the spec)
import type { TurboModule } from 'react-native';
import { TurboModuleRegistry } from 'react-native';
export interface Spec extends TurboModule {
add(a: number, b: number): number; // synchronous!
multiply(a: number, b: number): number;
asyncHash(input: string): Promise<string>;
}
export default TurboModuleRegistry.getEnforcing<Spec>('Calculator');
// 2. package.json - tell Codegen where the spec is
// "codegenConfig": {
// "name": "CalculatorSpec",
// "type": "modules",
// "jsSrcsDir": "./src"
// }
// 3. Kotlin implementation (android/src/main/java/...)
// class CalculatorModule(reactContext: ReactApplicationContext) :
// NativeCalculatorSpec(reactContext) {
//
// override fun add(a: Double, b: Double) = a + b
// override fun multiply(a: Double, b: Double) = a * b
// override fun asyncHash(input: String, promise: Promise) {
// promise.resolve(input.hashCode().toString(16))
// }
// override fun getName() = "Calculator"
// }
// 4. Swift implementation (ios/Calculator.swift)
// @objc(Calculator)
// class Calculator: NSObject {
// @objc func add(_ a: Double, b: Double) -> Double { a + b }
// @objc func multiply(_ a: Double, b: Double) -> Double { a * b }
// @objc func asyncHash(_ input: String, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
// resolve(String(input.hashValue, radix: 16))
// }
// }
// 5. Usage in JS
import NativeCalculator from './NativeCalculator';
const result = NativeCalculator.add(4, 6); // synchronous via JSI
const product = NativeCalculator.multiply(3, 7);
const hash = await NativeCalculator.asyncHash('hello');Tip
Tip
Practice Writing Native Modules RN CLI in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Creating custom Swift/Kotlin native modules with TypeScript Codegen contracts
Practice Task
Note
Practice Task - (1) Write a working example of Writing Native Modules RN CLI from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Writing Native Modules RN CLI is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.
Finished this lesson?