React Native — Native Modules Part 2 (IOS)

ReactOne
3 min readOct 20, 2021

--

Push Your APP Capability beyond what React Native Provide.

Photo by N Kamalov on Unsplash

Following to Part 1 where we covered basics about React Native architecture and and how to build a custom native module for android. please make sure to read Pate one before you continue:

Now we’ll cover the IOS Part and Break it down to:

  1. Setup Environment.

2. Start building module.

we will keep the same example an app have a button to show the phone Id onPress

1 — Setup Environment

To follow this example you need to create a React Native APP by running (or any existing React Native Project, we’re using TS you can use JS template too no worries ):

$ npx react-native init your-app-name --template react-native-template-typescript

2 — Start building module

Now you’re ready to :

  1. Create Custom Native Module Header.
  2. Create Corresponding Implementation file.
  3. Export Module To JavaScript.
  4. Test the Module from JavaScript.

1 — Create firs Header

We recommend using Xcode, it will help you to quickly resolve smaller errors like code syntax.

go to file/new/file select a header file then next, give it a name and set your target then click the Create button

Its better to name your file with any “RCT” or “RK” prefixes, so when you don’t specify a name for your module.where “RCT” refers to React. we’ll show that later.

and add the following to it:

Where RCTReactOneCustomMethod its an Objective-C class that implements the RCTBridgeModule protocol.

Next lets write the implementation for this Module at the same folder by creating RCTReactOneCustomMethod.m file with the following lines of code:

You notice that RCT_EXPORT_MODULE(); empty. as we talked earlier, If you don’t specify a name, the JavaScript module name will match the Objective-C class name. in case you want a specific naming:

#Wrong
RCT_EXPORT_MODULE("moduleName");
#Correct
RCT_EXPORT_MODULE(moduleName);

We profit and make it a Promise to show how to pas the resolver and reject so The native module can then be accessed in JS like this:

const { ReactOneCustomMethod } = NativeModules;

then accessing any method like this one getPhoneID()

its that simple and easy to implement, we covered the android part please refer to the Previous Article, also refer to official React Native Documentation

--

--

ReactOne

We are a small team of React Native and AWS experts