React Native: Android Native Modules
Did you know that you can use native code in React Native? Yes, you can. Java or Kotlin for Android platform, and Swift or Objective C for iOS. We'll talk about Native Modules, what they can be used for, and create a simple Native Module for Android.
The only thing required for this is that you know the native language of the platform.
React Native docs have an example for NativeModules, but I find it confusing for beginners, as they are making a module to communicate with the phone's calendar to create events from your app.
First, we need to create a new directory in the project.
android/app/src/main/java/com/your-project-name/ and create a directory called
date. This is where our module will live.
Every module needs to have 2 files.
DatePackage.java. Always name these files like you named your directory (e.g. StringModule.java, StringPackage.java).
DateModule.java we define our NativeModule, and we write code for it in that file.
DatePackage.java, we register our NativeModule and add it to
ReactPackage to be used from within React Native code.
Copy the following in the
This is boilerplate code, and here we just tell our
DateModule to extend
ReactContextBaseJavaModule, as it will give our module the ability to be recognized by React Native, and its lifecycle methods.
All Java native modules in Android need to implement the getName() method. This method returns a string, which represents the name of the native module
To get the current date and time in Java we need to import a class for that.
Add this at the top of
DateModule.java looks like this
Register the Module
After writing a native module, it must be registered with React Native. To do so, create a ReactPackage with your native module and register the ReactPackage with React Native. During initialization, React Native will loop through all packages and register each native module within each ReactPackage.
Add the following code to the
After this, all that's left to do is importing
DatePackage into the
DatePackage at the top of the file
Then locate ReactNativeHost’s
getPackages() method and add your package to the packages list
Testing what you've built
To import the newly created module in the ReactNative app we will use
react-native like this
This will return the DateTime string if everything is working correctly. If not you can
console.log(error) to see what went wrong.
Here is a sample code for creating a timer using this module.
Native Modules are a really powerful feature in React Native because you can go outside of React Native's scope and write your own logic, function, and code that isn't supported by default.
I used Native Modules in my latest project to write a function for detecting VPN. What are you going to use it for?