tezvyn:

Android-only native module called safely from JS

AI-drafted, machine-checkedintermediate
WHAT IT TESTS

building a platform-specific native module and guarding calls.

OUTLINE

write a ReactContextBaseJavaModule with an exported method, register it in a package, then guard the JS call with Platform.OS or a null check on the module.

WHAT THIS TESTS The interviewer wants to see you can author a platform-specific native module and, just as importantly, call it defensively so the absent iOS implementation never crashes the JS side.

A GOOD ANSWER COVERS On Android you create a Kotlin or Java class that extends ReactContextBaseJavaModule and implements getName to return the JS-facing name, for example ToastModule. You expose methods with the @ReactMethod annotation, such as show(message, duration), inside which you call the Android Toast API using the reactApplicationContext. You then create a ReactPackage that returns this module from createNativeModules, and register that package in your ReactNativeHost getPackages list (or it is autolinked if published as a library). From JavaScript you import NativeModules and read NativeModules.ToastModule. Because no iOS counterpart exists, that value is undefined on iOS, so you guard every call: check Platform.OS === 'android', or verify the module is truthy before invoking, and ideally wrap it in a small JS helper that no-ops or falls back on other platforms. This keeps the public API uniform while preventing a TypeError from calling a method on undefined.

COMMON WRONG ANSWERS Calling NativeModules.ToastModule.show(...) unconditionally crashes on iOS because the module is undefined. Forgetting to register the package means the module is missing even on Android. Assuming the method returns synchronously when it does work that should be async, or doing heavy work directly on the calling thread, can cause issues.

LIKELY FOLLOW-UPS Why is the module undefined on iOS rather than throwing at import? Because NativeModules is just a lookup map; missing keys are undefined. How do you provide an iOS fallback? Wrap in a JS module that branches on Platform and offers a JS alternative. How do you pass data back? Use promises, callbacks, or events.

ONE CONCRETE EXAMPLE A Toast helper: in JS, export function showToast(msg) { if (Platform.OS === 'android' && NativeModules.ToastModule) NativeModules.ToastModule.show(msg, 0); }. Calling showToast on Android pops a native Toast; on iOS it safely does nothing instead of crashing.

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.