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.
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
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
*Yehhhh You have successfully added a native module for both Android and iOS π₯³
*
3. Now Itβs time to implement π
- 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',
},
});
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)
Top comments (0)