DEV Community

Cover image for Creating a native module in react native.
Aman Kumar Singh
Aman Kumar Singh

Posted on

Creating a native module in react native.

I use React native on daily basis and some times i get into an issue for which i need a native solution. In this tutorial i will make a native method in java and i will call it form react native.

Lets start

File structure for creating native module

This is how your Empty react native Project will look like, here we will create a native module now in android studio.

This is how you open your project in android studio

Click on Open Existing project

Click in existing Project

Select your android folder of react native project.

Step 1

Create a new Java class

Create a new Java Class for timeBeing we will name it HelloPTModule

Here we will write some Java code


package com.whatsappcamera;

import android.provider.MediaStore;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import org.jetbrains.annotations.NotNull;

public class HelloPTModule extends ReactContextBaseJavaModule {
     public HelloPTModule (@Nullable ReactApplicationContext reactContext){
         super(reactContext);
     }
    @Override
    public String getName() {
        return "HelloPT";
    }

    @ReactMethod
    public void sayHello (String name, Callback cb) {
        try {
            String hello = "Hello " + name;
            cb.invoke(null, hello);
        } catch (Exception err) {
            cb.invoke(err, null);
        }
    }
}


Enter fullscreen mode Exit fullscreen mode

Lets understand what is written inside this

Every Native Module written for React Native to use always extends ReactContextBaseJavaModule. This class should have a public function getName which returns a string. Note that this string is important as we will use this identifier to call our native function form react native.

sayHello is the function which we will invoke form React Native.

Step 2

HelloPTPackage class creation

Here we will create another Java class for time being lets Name it HelloPTPackage

Your helloPTPackage will look like this

package com.whatsappcamera;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HelloPTPackage implements ReactPackage {
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(
            ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();

        modules.add(new HelloPTModule(reactContext));

        return modules;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3

Now we will register our package Open MainApplication, inside getPackages Method

MainActivity class things to add

add this line,

 packages.add(new HelloPTPackage());
Enter fullscreen mode Exit fullscreen mode

This step marks end of the process.

step 5 The Final step

To use this native module you have to import

import React from 'react';
import { NativeModules, SafeAreaView,Button} from 'react-native';
const { HelloPT } = NativeModules; // this is the same name we returned in getName function.

const App = () => {

  const Change = () => {
     HelloPT.sayHello("Aman", (err, msg) => {
      if (err) {
       console.log(err);
       return;
      }
     console.log(msg)
    })
  }

  return (
    <SafeAreaView>
        <Button onPress={Change} title="call native function" />
    </SafeAreaView>
  );
};
Enter fullscreen mode Exit fullscreen mode

When you click the button this will be in your terminal

YAY!! Terminal Output

Thanks for bearing with me 😊, Hope you enjoyed learning.
Please comment and share among your friends.

Top comments (2)

Collapse
 
enzou profile image
Enzo Perez

thanks for the article, is very useful!.. instead use cb can I use promises right? in that case, how would be the HelloPTModule file?

Collapse
 
amankumarsingh01 profile image
Aman Kumar Singh

It would look the same.