Creating a native module in react native.
Tags: reactnative, android, react, mobile
Published: 2022-03-16 18:36:37

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6mi4o0fp8yg1fd9nmds5.png)
  
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9hvcc46wathjc67f6q4x.png)

Click on Open Existing project 

![Click in existing Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4tsw8p1jbu0fyhg7hj55.png)

Select your android folder of react native project.


## Step 1

![Create a new Java class](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r91x61vfiholzrqu1439.png)

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

Here we will write some Java code 

```java

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);
        }
    }
}


```

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ok9owvqeekbfqig2hykb.png)

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

Your helloPTPackage will look like this 

```java
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;
    }
}
```

## Step 3 

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

![MainActivity class things to add](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fvdp7r74gvythttwh5he.png)
 
add this line,

```java
 packages.add(new HelloPTPackage());
```
 
This step marks end of the process.

## step 5 The Final step

To use this native module you have to import 

```jsx
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>
  );
};
```

When you click the button this will be in your terminal

![YAY!! Terminal Output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ugv1u0soffj37pniqnv.png)


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