Bird
Raised Fist0
React Nativemobile~20 mins

Linking native libraries in React Native - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Native Library Link Test
This screen tests linking a native library by displaying a native module's value.
Target UI
-------------------------
| Native Library Link Test |
|-------------------------|
| Native Value: [value]   |
|                         |
| [Refresh Button]        |
-------------------------
Display a value fetched from a linked native module
Add a button labeled 'Refresh' to reload the native value
Show loading indicator while fetching native value
Handle errors gracefully with an error message
Starter Code
React Native
import React, { useState, useEffect } from 'react';
import { View, Text, Button, ActivityIndicator, StyleSheet } from 'react-native';
import { NativeModules } from 'react-native';

const { SampleNativeModule } = NativeModules;

export default function NativeLibraryLinkTest() {
  const [nativeValue, setNativeValue] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    // TODO: Fetch native value on mount
  }, []);

  const fetchNativeValue = async () => {
    // TODO: Implement fetching native value from SampleNativeModule
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Native Library Link Test</Text>
      {/* TODO: Show loading, error or native value here */}
      <Button title="Refresh" onPress={fetchNativeValue} />
    </View>
  );
}

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

const { SampleNativeModule } = NativeModules;

export default function NativeLibraryLinkTest() {
  const [nativeValue, setNativeValue] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchNativeValue();
  }, []);

  const fetchNativeValue = async () => {
    setLoading(true);
    setError(null);
    try {
      const value = await SampleNativeModule.getValue();
      setNativeValue(value);
    } catch (e) {
      setError('Failed to load native value');
      setNativeValue(null);
    } finally {
      setLoading(false);
    }
  };

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Native Library Link Test</Text>
      {loading && <ActivityIndicator size="large" color="#0000ff" />}
      {!loading && error && <Text style={styles.errorText}>{error}</Text>}
      {!loading && !error && nativeValue !== null && (
        <Text style={styles.valueText}>Native Value: {nativeValue}</Text>
      )}
      <Button title="Refresh" onPress={fetchNativeValue} />
    </View>
  );
}

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

This React Native component demonstrates how to link and use a native library module.

We import NativeModules and extract SampleNativeModule, which is assumed to be linked natively.

On component mount, we call fetchNativeValue to asynchronously get a value from the native module.

While loading, an activity spinner shows. If an error occurs, a red error message appears. Otherwise, the native value is displayed.

The Refresh button lets the user reload the native value anytime.

This pattern helps verify that native libraries are properly linked and callable from JavaScript.

Final Result
Completed Screen
-------------------------
| Native Library Link Test |
|-------------------------|
| Native Value: 42        |
|                         |
| [Refresh Button]        |
-------------------------
When the screen loads, it shows a spinner briefly, then displays the native value.
Tapping the Refresh button reloads the native value and updates the display.
If loading fails, an error message appears in red.
Stretch Goal
Add a toggle switch to switch between light and dark mode for the screen.
💡 Hint
Use React Native's Appearance API or a state variable to toggle styles dynamically.

Practice

(1/5)
1. What is the main purpose of linking native libraries in a React Native app?
easy
A. To connect native code libraries so the app can use device features
B. To write JavaScript code faster
C. To create animations in React Native
D. To debug JavaScript errors

Solution

  1. Step 1: Understand linking in React Native

    Linking connects native code libraries to your React Native app so it can access device features like camera or GPS.
  2. Step 2: Identify the main purpose

    Since linking allows the app to use native device features, this is its main purpose.
  3. Final Answer:

    To connect native code libraries so the app can use device features -> Option A
  4. Quick Check:

    Linking = Connect native libraries [OK]
Hint: Linking connects native code to app features [OK]
Common Mistakes:
  • Thinking linking is for writing JavaScript faster
  • Confusing linking with animation creation
  • Assuming linking is for debugging only
2. Which command is used to manually link native libraries in React Native if auto-linking fails?
easy
A. react-native start
B. npm install react-native-link
C. npx react-native link
D. expo install

Solution

  1. Step 1: Recall the manual linking command

    The command to manually link native libraries is npx react-native link.
  2. Step 2: Compare options

    Only npx react-native link matches the correct manual linking command.
  3. Final Answer:

    npx react-native link -> Option C
  4. Quick Check:

    Manual linking command = npx react-native link [OK]
Hint: Use 'npx react-native link' for manual linking [OK]
Common Mistakes:
  • Using npm install react-native-link instead
  • Confusing with react-native start command
  • Using expo install which is unrelated
3. Given this React Native code snippet:
import { NativeModules } from 'react-native';

const { MyNativeModule } = NativeModules;

MyNativeModule.doSomething();
What must be true for MyNativeModule to work correctly?
medium
A. The JavaScript code must be minified
B. The app must use Expo managed workflow
C. The app must run only on iOS
D. The native library must be linked to the app

Solution

  1. Step 1: Understand native module usage

    Using NativeModules requires the native library to be linked so React Native can access native code.
  2. Step 2: Eliminate incorrect options

    Minifying JavaScript, running only on iOS, or using Expo managed workflow are unrelated to linking native modules.
  3. Final Answer:

    The native library must be linked to the app -> Option D
  4. Quick Check:

    NativeModules need linking [OK]
Hint: NativeModules require linked native libraries [OK]
Common Mistakes:
  • Thinking minification affects native linking
  • Assuming native modules work only on iOS
  • Confusing Expo managed workflow with native linking
4. You ran npx react-native link but your app crashes when using a native library. What is a likely cause?
medium
A. You did not install Node.js
B. You forgot to rebuild the app after linking
C. You used the wrong JavaScript import syntax
D. You are running the app on a simulator

Solution

  1. Step 1: Understand linking effects

    After linking native libraries, you must rebuild the app so native code changes take effect.
  2. Step 2: Identify the cause of crash

    If the app crashes, it is often because the native code was not compiled into the app yet due to missing rebuild.
  3. Final Answer:

    You forgot to rebuild the app after linking -> Option B
  4. Quick Check:

    Linking needs rebuild to apply [OK]
Hint: Always rebuild app after linking native libraries [OK]
Common Mistakes:
  • Ignoring the rebuild step after linking
  • Blaming JavaScript import syntax for native crashes
  • Assuming Node.js installation affects linking
  • Thinking simulator causes linking crashes
5. You want to use a native camera library in your React Native app. After installing it, auto-linking does not work. What is the best approach to fix this?
hard
A. Run npx react-native link and then rebuild the app
B. Delete the node_modules folder and reinstall packages
C. Only restart the Metro bundler without rebuilding
D. Switch to Expo managed workflow

Solution

  1. Step 1: Identify the problem with auto-linking

    If auto-linking fails, manual linking using npx react-native link is the recommended fix.
  2. Step 2: Complete the fix by rebuilding

    After linking, rebuilding the app is necessary to apply native code changes.
  3. Final Answer:

    Run npx react-native link and then rebuild the app -> Option A
  4. Quick Check:

    Manual link + rebuild fixes auto-link fail [OK]
Hint: Manual link and rebuild if auto-link fails [OK]
Common Mistakes:
  • Only reinstalling node_modules without linking
  • Restarting Metro bundler without rebuild
  • Switching to Expo without solving linking
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