NativeMethods
- React Native course
- Advanced
- Lesson 68/83
- 5 min
Learn native calls with NativeMethods.
NativeMethods
NativeMethods is the standard way to call functions on native modules. A native module's methods look like ordinary functions on the JS side. Example: NativeModules.Battery.getLevel() returns a promise; with await you get the battery level.
During the call parameters are relayed from JS to native via the bridge. Type conversion is automatic: a JS number becomes a native number, a JS string becomes a native string. But complex objects are not always supported; so parameters are kept simple.
Returning a promise
Native method calls usually return a Promise. So the call is awaited. Example: const level = await NativeModules.Battery.getLevel(). level carries the battery percentage.
Making a native method synchronous is possible but not recommended; because blocking the UI thread breaks animations. Staying asynchronous keeps UI smooth and makes error handling easier. Errors are caught with try/catch.
Practice Read the battery level
Complete the getBatteryLevel function. Import NativeModules from react-native. Read the level with const level = await NativeModules.Battery.getLevel() and return it.
Starter code
import { NativeModules } from 'react-native';
export async function getBatteryLevel() {
// read the level from the Battery module
}Sample solution
import { NativeModules } from 'react-native';
export async function getBatteryLevel() {
const level = await NativeModules.Battery.getLevel();
return level;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the NativeMethods parts
| Term | Meaning |
|---|---|
NativeModules.Battery |
Module name |
.getLevel() |
Method call |
await |
Waits for the promise |
promise |
Async result |
2 Why does a native method return a promise?
- Because it runs on the UI thread, may not return immediately
- Because using a promise is mandatory
- Because the module is not async
- Because JS cannot run synchronously Correct answer
Explanation: A native method runs on the UI thread; so it returns a promise.
3 Wait with await
const level = ____ NativeModules.Battery.getLevel();
const level = await NativeModules.Battery.getLevel();
Explanation: await waits for the promise result.