0
0
React Nativemobile~20 mins

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

Choose your learning style9 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.