Bird
Raised Fist0
React Nativemobile~20 mins

Why native modules extend capabilities in React Native - Build It to Prove It

Choose your learning style10 modes available
Build: Native Module Demo
This screen shows how React Native can use native modules to access device features not available in JavaScript alone.
Target UI
-------------------------
| Native Module Demo     |
|-----------------------|
| Device Info:          |
| [Loading...]          |
|                       |
| [Get Device Info]     |
-------------------------
Display a button labeled 'Get Device Info'.
When tapped, call a native module to get device info (e.g., device name or OS version).
Show the returned info below the button.
Handle loading state while fetching info.
Starter Code
React Native
import React, { useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';

export default function NativeModuleDemo() {
  const [deviceInfo, setDeviceInfo] = useState(null);
  const [loading, setLoading] = useState(false);

  const getDeviceInfo = () => {
    // TODO: Call native module here and update deviceInfo
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Native Module Demo</Text>
      <Text style={styles.label}>Device Info:</Text>
      <Text style={styles.info}>{loading ? 'Loading...' : deviceInfo || ''}</Text>
      <Button title="Get Device Info" onPress={getDeviceInfo} />
    </View>
  );
}

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

const { DeviceInfoModule } = NativeModules;

export default function NativeModuleDemo() {
  const [deviceInfo, setDeviceInfo] = useState(null);
  const [loading, setLoading] = useState(false);

  const getDeviceInfo = async () => {
    setLoading(true);
    try {
      const info = await DeviceInfoModule.getDeviceName();
      setDeviceInfo(info);
    } catch (e) {
      setDeviceInfo('Error fetching device info');
    }
    setLoading(false);
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Native Module Demo</Text>
      <Text style={styles.label}>Device Info:</Text>
      <Text style={styles.info}>{loading ? 'Loading...' : deviceInfo || ''}</Text>
      <Button title="Get Device Info" onPress={getDeviceInfo} />
    </View>
  );
}

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

This example shows how React Native uses native modules to access device features that JavaScript alone cannot reach. We import NativeModules from React Native and get a reference to a native module called DeviceInfoModule. This module is assumed to be implemented natively (in Java or Swift) and exposes a method getDeviceName that returns the device's name.

When the user taps the button, we call this native method asynchronously. We show a loading message while waiting. Once the info is received, we display it on screen. This demonstrates how native modules extend React Native's capabilities by bridging to platform-specific code.

Final Result
Completed Screen
-------------------------
| Native Module Demo     |
|-----------------------|
| Device Info:          |
| Pixel 7 Pro           |
|                       |
| [Get Device Info]     |
-------------------------
User taps 'Get Device Info' button.
Text below button changes to 'Loading...'.
After a short wait, device name (e.g., 'Pixel 7 Pro') appears.
If error occurs, shows 'Error fetching device info'.
Stretch Goal
Add a button to get the device OS version using another native module method.
💡 Hint
Create another native method like getOSVersion and call it similarly to getDeviceName.

Practice

(1/5)
1. Why do React Native apps use native modules?
easy
A. To make the app slower and less efficient
B. To write all app code in JavaScript only
C. To avoid using any native platform code
D. To access device features not available in JavaScript

Solution

  1. Step 1: Understand React Native limitations

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

    Native modules bridge JavaScript with native platform code to access those features.
  3. Final Answer:

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

    Native modules = access device features [OK]
Hint: Native modules add device features JavaScript lacks [OK]
Common Mistakes:
  • Thinking native modules replace JavaScript code
  • Believing native modules slow down the app
  • Assuming native modules are optional for all features
2. Which of the following is the correct way to import a native module in React Native?
easy
A. import { NativeModules } from 'react-native';
B. import NativeModules from 'react-native';
C. require('NativeModules');
D. import NativeModules from 'native-modules';

Solution

  1. Step 1: Recall React Native import syntax

    NativeModules is a named export from 'react-native', so it must be imported with curly braces.
  2. Step 2: Check each option

    import { NativeModules } from 'react-native'; uses correct syntax with curly braces; others are incorrect or invalid module names.
  3. Final Answer:

    import { NativeModules } from 'react-native'; -> Option A
  4. Quick Check:

    Correct import uses curly braces [OK]
Hint: Use curly braces to import named exports [OK]
Common Mistakes:
  • Omitting curly braces for named imports
  • Using wrong module names
  • Using require without assignment
3. What will the following React Native code output if the native module 'DeviceInfo' returns the device name 'Pixel 5'?
import { NativeModules } from 'react-native';
const { DeviceInfo } = NativeModules;

DeviceInfo.getDeviceName((name) => {
  console.log('Device:', name);
});
medium
A. Device: Pixel 5
B. Device: undefined
C. Error: getDeviceName is not a function
D. Device: null

Solution

  1. Step 1: Understand native module callback

    The native module 'DeviceInfo' calls the callback with the device name 'Pixel 5'.
  2. Step 2: Check console.log output

    The callback logs 'Device: Pixel 5' to the console.
  3. Final Answer:

    Device: Pixel 5 -> Option A
  4. Quick Check:

    Callback logs device name correctly [OK]
Hint: Callbacks print native data as expected [OK]
Common Mistakes:
  • Assuming synchronous return instead of callback
  • Expecting undefined if native module not linked
  • Confusing function names or parameters
4. You wrote this code to use a native module but get an error: TypeError: NativeModules.CameraModule.getPicture is not a function. What is the most likely cause?
medium
A. You forgot to import React
B. JavaScript syntax error in your code
C. The native module is not properly linked or registered
D. You used the wrong variable name for NativeModules

Solution

  1. Step 1: Analyze the error message

    The error says the function does not exist on the native module object.
  2. Step 2: Understand native module linking

    If the native module is not linked or registered correctly, its functions won't be available in JavaScript.
  3. Final Answer:

    The native module is not properly linked or registered -> Option C
  4. Quick Check:

    Linking issues cause missing native functions [OK]
Hint: Check native module linking if functions missing [OK]
Common Mistakes:
  • Assuming import errors cause this
  • Ignoring native build steps
  • Confusing variable names with linking problems
5. You want to create a React Native app that uses a native module to access the phone's biometric sensor for fingerprint authentication. Which of the following is the best approach?
hard
A. Write all biometric code in JavaScript without native modules
B. Use a native module to connect JavaScript with the platform's biometric API
C. Use only React Native UI components without any native code
D. Use a web API inside a WebView for biometric access

Solution

  1. Step 1: Identify biometric sensor access needs

    Biometric sensors require native platform APIs not accessible directly from JavaScript.
  2. Step 2: Choose the correct integration method

    Native modules bridge JavaScript with native biometric APIs for secure and efficient access.
  3. Step 3: Evaluate other options

    JavaScript alone or WebView cannot access biometric hardware securely or at all.
  4. Final Answer:

    Use a native module to connect JavaScript with the platform's biometric API -> Option B
  5. Quick Check:

    Native modules enable hardware access [OK]
Hint: Use native modules for hardware features like biometrics [OK]
Common Mistakes:
  • Trying to access hardware only with JavaScript
  • Ignoring security and platform API requirements
  • Using WebView for native 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