Navigating React Native: A Step-by-Step Guide to Convert HTML to String in React Native 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>
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 ??:
Now let’s get started ??
Step 1: Set Up Your 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:
inside the android/app/src/main/java/com/yourapp/ directory.
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:
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
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
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
Yehhhh You have successfully added a native module for both Android and iOS ??
3. Now It’s time to implement ??
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:
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)