Bird
Raised Fist0
React Nativemobile~20 mins

Native modules concept in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: NativeModulesDemo
This screen shows how to use a native module in React Native to get the device's current battery level and display it.
Target UI
-------------------------
| Battery Level Demo     |
|-----------------------|
| Battery Level: -- %   |
|                       |
| [Refresh Battery Level]|
-------------------------
Display the current battery level as a percentage.
Use a native module to get the battery level (simulate with a mock native module).
Add a button labeled 'Refresh Battery Level' that updates the displayed battery level when pressed.
Show a loading indicator while fetching the battery level.
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, Button, ActivityIndicator, StyleSheet } from 'react-native';
import { NativeModules } from 'react-native';

const { BatteryModule } = NativeModules;

export default function NativeModulesDemo() {
  const [batteryLevel, setBatteryLevel] = useState(null);
  const [loading, setLoading] = useState(false);

  const fetchBatteryLevel = async () => {
    // TODO: Call native module method to get battery level
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Battery Level Demo</Text>
      <Text style={styles.batteryText}>Battery Level: {batteryLevel !== null ? `${batteryLevel} %` : '--'}</Text>
      {loading && <ActivityIndicator size="small" color="#0000ff" />}
      <Button title="Refresh Battery Level" onPress={fetchBatteryLevel} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  },
  title: {
    fontSize: 24,
    marginBottom: 20
  },
  batteryText: {
    fontSize: 18,
    marginBottom: 10
  }
});
Task 1
Task 2
Task 3
Solution
React Native
import React, { useState } from 'react';
import { View, Text, Button, ActivityIndicator, StyleSheet } from 'react-native';
import { NativeModules } from 'react-native';

const { BatteryModule } = NativeModules;

export default function NativeModulesDemo() {
  const [batteryLevel, setBatteryLevel] = useState(null);
  const [loading, setLoading] = useState(false);

  const fetchBatteryLevel = async () => {
    setLoading(true);
    try {
      const level = await BatteryModule.getBatteryLevel();
      setBatteryLevel(level);
    } catch (error) {
      setBatteryLevel(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Battery Level Demo</Text>
      <Text style={styles.batteryText}>Battery Level: {batteryLevel !== null ? `${batteryLevel} %` : '--'}</Text>
      {loading && <ActivityIndicator size="small" color="#0000ff" />}
      <Button title="Refresh Battery Level" onPress={fetchBatteryLevel} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 16
  },
  title: {
    fontSize: 24,
    marginBottom: 20
  },
  batteryText: {
    fontSize: 18,
    marginBottom: 10
  }
});

This example shows how to use a native module in React Native. The BatteryModule is assumed to be a native module that provides a method getBatteryLevel() returning a Promise with the battery percentage.

We use React state to store the battery level and a loading flag. When the user taps the button, fetchBatteryLevel calls the native module method asynchronously. While waiting, a spinner shows. When the value arrives, we update the UI with the battery level.

This pattern helps React Native apps access device features not available in JavaScript alone by bridging to native code.

Final Result
Completed Screen
-------------------------
| Battery Level Demo     |
|-----------------------|
| Battery Level: 87 %   |
|                       |
| [Refresh Battery Level]|
-------------------------
User taps 'Refresh Battery Level' button.
Loading spinner appears below battery level text.
Battery level updates to new value after fetching from native module.
Stretch Goal
Add error handling to show an alert if fetching battery level fails.
💡 Hint
Use try-catch in fetchBatteryLevel and React Native's Alert.alert to show an error message.

Practice

(1/5)
1. What is the main purpose of native modules in React Native?
easy
A. To access device features not available in JavaScript
B. To style components using CSS
C. To manage app navigation
D. To write UI components in JavaScript

Solution

  1. Step 1: Understand React Native limitations

    JavaScript in React Native cannot access all device hardware or OS features directly.
  2. Step 2: Role of native modules

    Native modules are written in native code to bridge this gap and provide access to those features.
  3. Final Answer:

    To access device features not available in JavaScript -> Option A
  4. Quick Check:

    Native modules = access device features [OK]
Hint: Native modules bridge JavaScript to device features [OK]
Common Mistakes:
  • Thinking native modules are for styling
  • Confusing native modules with navigation libraries
  • Believing native modules are UI components
2. Which syntax correctly imports a native module named CameraModule in React Native?
easy
A. import CameraModule from 'react-native';
B. import { NativeModules } from 'react-native'; const { CameraModule } = NativeModules;
C. const CameraModule = require('CameraModule');
D. import CameraModule from 'NativeModules';

Solution

  1. Step 1: Recall native module import pattern

    Native modules are accessed via the NativeModules object from 'react-native'.
  2. Step 2: Correct destructuring syntax

    We import NativeModules, then extract CameraModule from it using const { CameraModule } = NativeModules.
  3. Final Answer:

    import { NativeModules } from 'react-native'; const { CameraModule } = NativeModules; -> Option B
  4. Quick Check:

    NativeModules destructuring = correct import [OK]
Hint: Always import NativeModules then destructure [OK]
Common Mistakes:
  • Importing native module directly from 'react-native'
  • Using require without NativeModules
  • Wrong import source string
3. Given this code snippet, what will be logged if the native module method getBatteryLevel returns 85 asynchronously?
import { NativeModules } from 'react-native';
const { BatteryModule } = NativeModules;

BatteryModule.getBatteryLevel().then(level => {
  console.log('Battery level is: ' + level);
});
medium
A. Error: getBatteryLevel is not a function
B. Battery level is: undefined
C. Battery level is: [object Promise]
D. Battery level is: 85

Solution

  1. Step 1: Understand asynchronous method call

    getBatteryLevel returns a Promise that resolves to 85.
  2. Step 2: Analyze the .then callback

    The callback receives the resolved value 85 and logs 'Battery level is: 85'.
  3. Final Answer:

    Battery level is: 85 -> Option D
  4. Quick Check:

    Promise resolves to 85, logged correctly [OK]
Hint: Promises log resolved value inside .then [OK]
Common Mistakes:
  • Logging the Promise object instead of resolved value
  • Assuming synchronous return
  • Confusing undefined with error
4. What is wrong with this native module usage code?
import { NativeModules } from 'react-native';
const { LocationModule } = NativeModules;

const location = LocationModule.getCurrentLocation();
console.log(location);
medium
A. getCurrentLocation likely returns a Promise but is used synchronously
B. getCurrentLocation is not imported correctly
C. NativeModules cannot be destructured
D. console.log cannot print location objects

Solution

  1. Step 1: Identify asynchronous method usage

    Native module methods like getCurrentLocation usually return Promises.
  2. Step 2: Check synchronous usage

    The code assigns the Promise to location and logs it immediately, not waiting for resolution.
  3. Final Answer:

    getCurrentLocation likely returns a Promise but is used synchronously -> Option A
  4. Quick Check:

    Async method used without await or .then [OK]
Hint: Async native methods need await or .then [OK]
Common Mistakes:
  • Ignoring Promise nature of native methods
  • Trying to destructure NativeModules incorrectly
  • Assuming console.log can't print objects
5. You want to create a native module to access the phone's flashlight. Which steps are necessary to correctly use this native module in your React Native app?
hard
A. Write native code, but no need to register module or import it in JavaScript
B. Write JavaScript code only, import flashlight from 'react-native', call methods synchronously
C. Write native code for flashlight, register module, import NativeModules, call methods asynchronously
D. Use only React Native UI components, no native code needed

Solution

  1. Step 1: Develop native code and register module

    You must write native code (Java/Swift/Obj-C) to control flashlight and register it with React Native.
  2. Step 2: Import and call from JavaScript

    Import NativeModules, extract your flashlight module, and call its methods asynchronously.
  3. Final Answer:

    Write native code for flashlight, register module, import NativeModules, call methods asynchronously -> Option C
  4. Quick Check:

    Native code + registration + async calls = correct usage [OK]
Hint: Native module needs native code, registration, async JS calls [OK]
Common Mistakes:
  • Skipping native code or registration
  • Calling native methods synchronously
  • Assuming React Native UI covers hardware access
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard