0
0
React Nativemobile~5 mins

Native modules concept in React Native

Choose your learning style9 modes available
Introduction

Native modules let your React Native app use features that are only available in the phone's system. This helps your app do more things by talking directly to the phone's special parts.

You want to use the phone's camera in a way React Native doesn't support by default.
You need to access the phone's sensors like the accelerometer or gyroscope.
You want to use a special feature from iOS or Android that React Native can't do alone.
You want to improve app speed by running some code directly on the phone's system.
You want to reuse existing native code from another app inside your React Native app.
Syntax
React Native
// Example of a native module in JavaScript
import { NativeModules } from 'react-native';
const { MyNativeModule } = NativeModules;

MyNativeModule.myMethod('Hello', (result) => {
  console.log(result);
});

You import native modules from NativeModules in React Native.

Native modules are written in native code (Java/Kotlin for Android, Objective-C/Swift for iOS) and linked to JavaScript.

Examples
This calls a native method to show a toast message on the phone.
React Native
// Calling a native method
MyNativeModule.showToast('Hi!');
This asks the native code for the device name and prints it.
React Native
// Getting a value from native code
MyNativeModule.getDeviceName((name) => {
  console.log('Device name is ' + name);
});
Sample App

This React Native app has a button. When you press it, it calls a native module method to get a welcome message from the phone's native code. Then it shows that message on the screen.

React Native
import React from 'react';
import { View, Button, NativeModules, Text } from 'react-native';

export default function App() {
  const [message, setMessage] = React.useState('');

  const showNativeMessage = () => {
    NativeModules.MyNativeModule.getWelcomeMessage((msg) => {
      setMessage(msg);
    });
  };

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Button title="Get Native Message" onPress={showNativeMessage} />
      <Text>{message}</Text>
    </View>
  );
}
OutputSuccess
Important Notes

Native modules require writing code in native languages and linking it to React Native.

Always test native modules on real devices or emulators because they depend on platform features.

Use native modules only when React Native does not provide the needed feature.

Summary

Native modules connect React Native apps to phone features not available in JavaScript.

They are written in native code and called from JavaScript.

Use them to access special hardware or improve performance.