How to write a simple native module in React Native

Hi everyone, this is my first time of writing a blog, so I will keep it as simple as possible. My intention of writing this one is to record any thing new that I’ve learned. So my goal is try to build a very simple native module in iOS and use it in React Native project. Then I will learn how to wrap this modules as a plugin to reused it in other projects and finally make it as a npm package that available for everyone.

So I will split this one into 3 post, and here we are at the first one. “How to build a simple native module in React Native”

Let’s start

Open your project on xcode, and create 2 files SimpleNativeModule.h and SimpleNativeModule.m under your project folder

Here is a content of SimpleNativeModule.h (.h is an alias for .header)

See. Nothing special, it’s just a definition of an interface. But if we want to make React Native understand this module, we have to implement RCTBridgeModule since every communication between Js part and Native part always done via that bridge.

And then we implement this interface by editing SimpleNativeModule.m (.m is an alias for implementation)

At line 13 the purpose of RCT_EXPORT_MODULE() is allow you to import this native modules in .js file like this

And if you want to export that module into a specific name, you just need to call RCT_EXPORT_MODULE(monkey) then you can call something like this in .js file

And at the line 15 to 18 we’re exported a function named getThingsFromNative, and take in a callback function. Then we will call that function in our app like this

BOOM, we’re done.

Please don’t ask me anything about native code, I know nothing :D . This is just to determine how you can build a really simple native module and export it to use in your .js file.

Thanks so much for reading. There’s will be another post for android as soon as I find out how to do it on android :D