DEV Community

Bibhuti
Bibhuti

Posted on

1 1

Navigating React Native: A Step-by-Step Guide to Convert HTML to String in Native Modules Using Native Module ๐ŸŒ

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>

Enter fullscreen mode Exit fullscreen mode
Hey, this is React Native

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

My project name is rnnativemodule

npx react-native init rnnativemodule
Enter fullscreen mode Exit fullscreen mode

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

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);
  }
}
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode
Finally, add WebViewPackage() in MainApplication.java inside your protected List<ReactPackage> getPackages:
Enter fullscreen mode Exit fullscreen mode

like:

Image description

That's it! We successfully created for Android ๐Ÿฅณ

Now for IOS

for IOS, open your Xcode by following command:

xed ios
Enter fullscreen mode Exit fullscreen mode

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
  }

}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Now Clean Build Folder and Build your project

Your Swift file process

Image description

Image description

Image description

Image description

Image description

*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 =

Hey, this is React Native

;

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',
  },
});
Enter fullscreen mode Exit fullscreen mode

Result:

Image description

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)

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up