React Native Bridge with Kotlin

Valdio Veliu
ProAndroidDev
Published in
8 min readJan 21, 2018

--

React Native, despite being one of the most preferred cross-platform in mobile development, has its limitations too. There may be some features that are not implemented yet in React Native or some device-specific features that are not supported by this development platform. So we can use native modules to fill the gap.

Why do we need native modules in React Native apps?

Who can really say! Maybe you want to make platform-specific code or want to reuse some existing code. For whatever the reason, React Native allows you to create your own native modules and expose them to JavaScript. The whole process is described in depth in the Native Modules Android documentation.

If you want to get acquainted with the technical part of the topic, I strongly suggest you read the documentation first. As they explain in detail each step in which native Android modules are exposed to React code.

In the documentation, you can find a detailed example of how to bridge native Java modules to React Native. But what about Kotlin? Since Google I/O 2017, Kotlin is to a first-class language in Android.

In this post, I will focus on one question. How to bridge native Kotlin modules and UI components to React Native apps? So here we are! Lets bridge Kotlin to React Native.

Keep in mind that in the post I will focus on the Android side of the app. This is not an ultimate guide into native module bridging in IOS and Android. Rather, I will go through step by step the process needed to compile Kotlin code as native modules in React Native projects. And since the React Native build versions are a bit outdated, there will be quite a few changes in the build files of the Android project until we finally get to the Kotlin code.

Are you feeling lazy? Jump right to the final project.

Create a new React Native project

I will go through using the react native CLI commands, but if you prefer to use Expo the process is the same. Just create a new app and run it on your device.

Let’s start by creating a new project. Open your terminal, cd to your development folder and create a new project.

react-native init ReactNative_Kotlin_Bridge

After the project is created, cd into the projects folder and run the app in your Android device.

react-native run-android

Make sure your app works properly.

Including Kotlin to the project

Now that the react Native app is created we like to include Kotlin to the android project.

Open the project in your text editor and navigate to your android project. I will be using Atom as my editor in this example, but I strongly suggest you open the android section of this project in Android Studio. What Android Studio will provide, is perfect indexing of the project and if you have some missing packages and dependencies it will suggest to install them. Since we are going to add some extra packages in the project Gradle files, you will definitely have some packages to install.

Android folder structure

Add Kotlin to the Gradle build files

There are quite a few changes to be made in the project in order to run Kotlin code.

Lest start by editing the build.gradle file at the project level.

Project level build.gradle

At this time React Native uses an outdated Gradle build version. On the other hand, the latest Gradle version available at this time is version 4.1. Therefore I am going to update the Gradle version.

If you have any problems with the change in the Gradle version check out the tutorial on how to Migrate to Android Gradle 3.0.0. This Gradle version has a far superior build speed than its predecessor, so why not ease our life with faster builds.

Open the project-level build.gradle and make the following changes.

Include the Kotlin version:

buildscript {  ext.kotlin_version = '1.2.10'  //...}

Make sure to add google() in the buildscript.repositories

buildscript{  repositories {    google()    //...  }}

Also, add google() in allprojects.repositories

allprojects {  repositories {    //...    google()  }}

Upgrade the build tools version to 3.0.1 and add the following classpath in the dependencies to include the Kotlin Gradle plugin .

dependencies {  classpath 'com.android.tools.build:gradle:3.0.1'  classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"}

If you have other dependencies make sure you add them to.

Upgrade Gradle version

Since we are upgrading our Gradle version, in the Gradle section of the project we are upgrading to Gradle 4.1. Make sure you open the “gradle” folder and not “.gradle”.

Upgrading the Gradle version

Open gradle-wrapper.properties and edit the distributionUrl

Replace the following line:

# distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip# Replace with: distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

Application modules build.gradle (app)

Now that we upgraded the build tool version, its time to include Kotlin to the project. FINALLY!

Open build.gradle (app) and we have to make a few changes.

Include Kotlin to the project

At the top of the file, include the following Kotlin plugins.

apply plugin: "com.android.application" // already exists in build.gradleapply plugin: "kotlin-android"apply plugin: "kotlin-android-extensions"

In the dependencies section add the following dependency

dependencies {implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"//...}

After you have followed all this steps, now you can test your app.

cd into the project folder and run the React Native app. Don’t just hot-reload the app.

Run in the terminal:

react-native run-android

Sometimes the command fails for some reason! I’m not quite sure why! Just run it a few times so the project can sync with the new gradle version.

It might take a while as the Android project will sync with the new Gradle version and will download all the missing packages and dependencies. If the project runs successfully you are in luck. And for some reason the project doesn't run successfully, you might have some missing dependencies or SDK packages. To make the fixes, open the android folder of the React Native project using Android Studio and sync the Gradle from there. It will show all whats wrong with your project and give you suggestions on how to fix the issues. Just sync everything and fix the project and you are good to go.

We can now bridge Kotlin in React Native. Yea!

Finally, here we are! We can run native Kotlin code in our project. I’m assuming you read the React Native article on native modules in Android that I mentioned before. In the post, it explains that native modules usually extend the ReactContextBaseJavaModule class and implement the required functions required by JavaScript to bridge to this modules. Also in Android, native modules have to be registered in order to be accessed by JavaScript.

On the documentation you will find an example on how to create a native Java Toast message in Android. If you are familiar with that example, I migrated the complete Java example into Kotlin code. You can find the native Kotlin module on the final project on Github. The explanation about the methods is the same as in the documentation. So you wont have any difficulties if you want to follow along with the same example featured in the documentation. Also, I kept the function and class names same as in the documentation example.

Further on in this post, I will cover another example on how to run native Kotlin Activities by using the React Native native module bridge. I created a video stream Activity, completely written in Kotlin that plays a video at a provided URL. Since we want to utilize the native module bridge, I am going to pass the streaming URL and the video title from React Native. The VideoStreamingActivity will play the video and display its title. This is not a complex Activity, as I wanted to keep things simple and focus more on creating the native module bridge.

Kotlin Hands on!

Creating the Kotlin video stream Activity

It’s time to write some Kotlin.
Now that we created the React Native — Kotlin bridge it’s time to put it to a test. So let’s start by creating three Kotlin classes. Create a folder inside the project package, KotlinVideoStreaming.

Inside the KotlinVideoStreaming folder create the following files. Kotlin files end with ‘.kt’.

VideoStreamingActivity.kt // the video streaming activity

StreamPackage.kt // used to register the native module

StreamManager.kt // used to start the Kotlin Activity and implement the getName() function

In the res folder create the folderlayout , because it is not present when creating the React Native app. Inside that folder create a layout file for the activity.

activity_video_streaming.xml // layout file for VideoStreamingActivity

Inside this layout file add the following:

Inside the VideoStreamingActivity file pase the followin code for the Activity.

Don’t focus too much on the code, the main objective here is testing the Kotlin native module. The Activity expects two strings passed through the intent containing the streaming URL and the video title. The rest of the code is related to the video stream functionalities.
If you are following along with a different package name, make sure you update the one already provided in this class. The same is true even for the other two classes.

Next step is to register the activity. Open AndroidManifest.xml and add the following code alongside the other Activities generated by React Native.

<activity android:name=".KotlinVideoStreaming.VideoStreamingActivity" />

In the StreamManager file paste the following code:

This class implements the necessary functionalities to run the native module and implements the getName() function which registers the native Kotlin module with the React Native bridge.

In the StreamPackage file paste the follwoing:

This class is used to register the native module with the application. So we now head out to MainApplication.java to register the module. In MainApplication.java, first of all, add the import of the video stream module.

import com.reactnative_kotlin_bridge.KotlinVideoStreaming.StreamPackage;

Then, we have to register the Kotlin module to the getPackages() method. Like the following:

@Overrideprotected List<ReactPackage> getPackages() {  return Arrays.<ReactPackage>asList(    new MainReactPackage(),    new StreamPackage()  );}

That’s it! We are all ready to go from the Kotlin part.

Now let’s make use of the Kotlin module. In React native create a new file, KotlinVideoStream.js and paste the following code:

import {NativeModules} from 'react-native';module.exports = NativeModules.KotlinVideoStream;

This will import the module and we can now use it in the app like the following example.

import KotlinVideoStream from './KotlinVideoStream';//...KotlinVideoStream.playVideoStream(  "Title",  "StreamURL");

In React Native we can now call the exposed method in the StreamManager class, playVideoStream() through which we can utilize our Kotlin module.

Conclusions

Thank you for reading this far. If you are having trouble configuring the project yourself, check out the final project on Github. In the final project, I also included the Kotlin Toast module featured in the react documentation.

Have a look at the final app.

--

--