1. React Native tutorial

Native Modules in react native

Create your Native Module (IOS)

Introduction

A Native Module is simply an Objective-C Class that implements the RCTBridgeModule protocol.

Example

In your Xcode project create a new file and select Cocoa Touch Class, in the creation wizard choose a name for your Class (e.g. NativeModule), make it a Subclass of: NSObject and choose Objective-C for the language.This will create two files NativeModuleEx.h and NativeModuleEx.m.You will need to import RCTBridgeModule.h to your NativeModuleEx.h file as it follows:

#import <Foundation/Foundation.h>
import "RCTBridgeModule.h"
@interface NativeModuleEx : NSObject <RCTBridgeModule>
@end

In your NativeModuleEx.m add the following code:

import “NativeModuleEx.h”

@implementation NativeModuleEx
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(testModule:(NSString *)string )
{
NSLog(@"The string '%@' comes from JavaScript! ", string);
}
@end

RCT_EXPORT_MODULE() will make your module accessible in JavaScript, you can pass it an optional argument to specify its name. If no name is provided it will match the Objective-C class name.RCT_EXPORT_METHOD() will expose your method to JavaScript, only the methods you export using this macro will be accessible in JavaScript.Finally, in your JavaScript you can call your method as it follows:

import { NativeModules } from 'react-native';
var NativeModuleEx = NativeModules.NativeModuleEx;
NativeModuleEx.testModule('Some String !');

If you like this post, don’t forget to share 🙂

This article is written by our awesome writer
Comments to: Native Modules in react native

Your email address will not be published. Required fields are marked *

Attach images - Only PNG, JPG, JPEG and GIF are supported.

New Dark Mode Is Here

Sign In to access the new Dark Mode reading option.

Join our Newsletter

Get our monthly recap with the latest news, articles and resources.

By subscribing you agree to our Privacy Policy.

Latest Articles

Explore Tutorials By Categories

About

Codeverb is simply an all in one interactive learning portal, we regularly add new topics and keep improving the existing ones, if you have any suggestions, questions, bugs issue or any other queries you can simply reach us via the contact page

Login

Welcome to Codeverb

Ready to learn something new?
Join Codeverb!

Read Smart, Save Time
  •  
    Strength indicator
  •  
  •  
    Log In | Lost Password