Navigating React Native: A Step-by-Step Guide to Convert HTML to String in Native Modules Using Native Module 🌐
Tags: reactnative, nativemodule, react, crossplatform
Published: 2024-01-28 21:22:43

**Understanding the Need: Why Convert HTML to String? 🤔**

Imagine you have a compelling HTML representation of content like



```
<h1>Hey, this is React Native</h1>

```


```
Hey, this is React Native

```


However, directly displaying HTML in a notification is not the most user-friendly approach. The key lies in converting this HTML to a string first. This process ensures a clean and readable presentation, making it ideal for various scenarios, including notifications.


**Scenarios Where HTML to String Conversion Shines 🌟:**

Notifications: As mentioned, converting HTML to a string is crucial when delivering content in notifications.
Text Display: When rendering HTML content within a Text component in React Native, having it in string format simplifies the display process.
Data Processing: In scenarios where data manipulation or processing is involved, having HTML in string form facilitates smoother operations.

**Now let’s get started 😀**


**Step 1: Set Up Your React Native Project 🚀**
Create a React Native project:

```
npx react-native init YourProjectName
```


My project name is rnnativemodule

```
npx react-native init rnnativemodule
```




**Step 2: Create the Native Module**


**For Android**
For Android we have to create two files:

- WebViewModule.java
- WebViewPackage.java


inside the android/app/src/main/java/com/yourapp/ directory.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gl4qwnvr70up32wrzh3p.png)


Now Add code in WebViewModule.java file:


```
package com.rnnativemodule;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.text.Html;
import android.util.Log;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.util.Random;

public class WebViewModule extends ReactContextBaseJavaModule {

  public WebViewModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  @Override
  public String getName() {
    return "WebViewModule";
  }

  @ReactMethod
  public void convertHTML(String html, com.facebook.react.bridge.Callback callback) {
      CharSequence output = Html.fromHtml(html);
      String htmlOutput = output.toString();
      callback.invoke(htmlOutput);
  }
}
```


Now for WebViewPackage.java


```
package com.rnnativemodule;
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 WebViewPackage implements ReactPackage {

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();
        modules.add(new WebViewModule(reactContext)); // Your native module name
        return modules;
    }

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

```



```
Finally, add WebViewPackage() in MainApplication.java inside your protected List<ReactPackage> getPackages:
```


like:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/goqaovjglr9owkblsz83.png)



**That's it! We successfully created for Android 🥳**



**Now for IOS**

for IOS, open your Xcode by following command:


```
xed ios
```



Or you can open your rnnativemodule.xcworkspace file

Now right-click on your project name and create New File
Click to Swift File
Save As: WebViewModule
Click to Create
It will ask you for Create Bridging Header click to Create Bridging Header
That’s it,

Add below code in WebViewModule.swift file



```
//
//  WebViewModule.swift
//  rnnativemodule
//
//  Created by Bibhuti Swain on 29/01/24.
//

import Foundation
import React
import UIKit


@objc(WebViewModule)
class WebViewModule:NSObject{
  
  @objc func convertHTML(_ html: String, callback: @escaping RCTResponseSenderBlock) {
      if let attributedString = try? NSAttributedString(data: html.data(using: .utf8)!, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) {
          let plainText = attributedString.string
          callback([plainText])
      } else {
          callback([""])
      }
  }

  @objc func constantsToExport() -> [AnyHashable : Any]! {
      return ["convertHtml": "value"] 
  }

  @objc static func requiresMainQueueSetup() -> Bool {
      return true
  }

}
```



Now Create an Objective-C file by

Right click on your project name
Click New File
Select Objective-C file
Click Next
Enter file name as WebViewModule
Click to Next
Cool.


Now add below code into your WebViewModule.m file

```
//
//  WebViewModule.m
//  rnnativemodule
//
//  Created by Bibhuti Swain on 29/01/24.
//

#import <Foundation/Foundation.h>
#import "React/RCTBridgeModule.h"
#import <React/RCTEventEmitter.h>

@interface RCT_EXTERN_MODULE(WebViewModule,NSObject)

RCT_EXTERN_METHOD(convertHTML:(NSString *)html callback:(RCTResponseSenderBlock)callback)

@end
```

Now Clean Build Folder and Build your project

Your Swift file process



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qz8d21o4shkxyx2gqppp.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5ogg82e4lr6eyjsssh1f.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5w66zz6txfa75xbl6izp.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/04xys8m1duqc1zrz2zve.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6631qs3hxsncpd7sjqsx.png)


**Yehhhh You have successfully added a native module for both Android and iOS 🥳
**

**3. Now It’s time to implement 🚀**


1. open your App.tsx or App.js file or whichever file you want to use

`import { NativeModules } from 'react-native';
const { WebViewModule } = NativeModules;`


Add some dummy HTML:

`const html = `<h1>Hey, this is React Native</h1>`;
`

Use your convertHTML function by calling:

`WebViewModule.convertHTML(html, (result: string) => {
   console.log(result); // the result contains your actual result
});`


Here is my App.tsx file:

```
import React, {useState} from 'react';
import {
  NativeModules,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

const {WebViewModule} = NativeModules;

const App = () => {
  const [convertToString, setConvertToString] = useState('');
  const html = `<h1>Hey this is react  native</h1>`;

  return (
    <View style={styles.container}>
      <Text style={styles.text}>{html}</Text>
      <Text style={styles.text}>After HTML to String : {convertToString}</Text>

      <TouchableOpacity
        style={styles.btn}
        onPress={() => {
          WebViewModule.convertHTML(html, (result: string) => {
            setConvertToString(result); // the result contain your actual result
          });
        }}>
        <Text style={styles.btnText}>Convert to String</Text>
      </TouchableOpacity>
    </View>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 18,
    marginBottom: 10,
  },
  btn: {
    marginTop: 40,
    backgroundColor: '#e4aa3f',
    borderRadius: 30,
    padding: 10,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 20,
  },
  btnText: {
    fontSize: 18,
    color: '#fff',
  },
});
```



**Result:**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbe5mcdyr7sr132rjk96.png)



Congratulations!🙌 You’ve successfully integrated a native module to convert HTML to a string in your React Native project. Whether you’re displaying notifications or processing data, this step-by-step guide empowers you to seamlessly handle rich HTML content in your React Native applications. Go ahead, explore the possibilities, and elevate your React Native development experience! 🚀

Github repo: bibhuti9/RN-Native-Module (github.com)