I have been playing around with native ui components and integrating them into a React Native App.
What I’m trying to do is create a messaging system within my app so users can send a message and reply to messages, but the way I want the messages to be displayed is using WebView’s because I want to show links and iframes in the WebView or the message item. I was using simply a Text Component which works well but cannot display links and iframes of YouTube videos in the component.
So I went and developed a Native UI Component that has a WebView in a linear layout and returning this Native Ui Component using View Manager, ReactPackage, JavaScript Interface and the Custom View that returns the Linear Layout that contains the WebView.
This is my View MAnager:
<code> package com.poller;
import android.graphics.Color;
import android.view.ViewGroup.LayoutParams;
import android.text.Html;
import android.widget.TextView;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.opengl.GLSurfaceView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.text.ReactTextShadowNode;
public class MyCustomViewManager extends SimpleViewManager<CustomView> {
public static final String REACT_CLASS = "MyCustomView";
ThemedReactContext reactContext;
public String getName() {
protected CustomView createViewInstance(ThemedReactContext reactContext) {
/**String html = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>HTML5 Boilerplate</title></head><body style='margin:0;padding:0;'><h1>Page Title 2</h1></body></html>";
html += "window.onload = function(){";
html += "javascript:JSInterface.ResizeWebView(document.body.scrollHeight)";
this.reactContext = reactContext;
layout = new CustomView(reactContext);
@ReactProp(name = "messageId")
public void setMessageId(LinearLayout view, int messageId) {
layout.setMessageId(String.valueOf(messageId));
@ReactProp(name = "message")
public void setWebviewHtml(LinearLayout view, String html) {
String uniqueId = UUID.randomUUID().toString().replace("-", "");
uniqueId = "APPJS" + uniqueId;
//Toast.makeText(reactContext, "uniqueId: " + uniqueId, Toast.LENGTH_SHORT).show();
html = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>HTML5 Boilerplate</title><script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js' integrity='sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==' crossorigin='anonymous' referrerpolicy='no-referrer'></script></head><body style='margin:0;padding:0;word-wrap:break-word;'>" + html + "</body></html>";
//oast.makeText(reactContext, "html: " + html, Toast.LENGTH_SHORT).show();
html += "$(document).ready(function() {";
html += "javascript:" + uniqueId + ".ResizeWebView($(document).height())";
layout.setWebviewHtml(html, uniqueId);
public @Nullable Map getExportedCustomDirectEventTypeConstants() {
return MapBuilder.of("myCallback",
MapBuilder.of("registrationName", "myCallback"));
<code> package com.poller;
import android.graphics.Color;
import android.view.ViewGroup.LayoutParams;
import android.text.Html;
import android.widget.TextView;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.opengl.GLSurfaceView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.text.ReactTextShadowNode;
import java.util.Map;
import java.util.UUID;
public class MyCustomViewManager extends SimpleViewManager<CustomView> {
public static final String REACT_CLASS = "MyCustomView";
CustomView layout;
WebView webView;
int h = 0;
int w = 0;
ThemedReactContext reactContext;
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected CustomView createViewInstance(ThemedReactContext reactContext) {
/**String html = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>HTML5 Boilerplate</title></head><body style='margin:0;padding:0;'><h1>Page Title 2</h1></body></html>";
html += "<script>";
html += "window.onload = function(){";
html += "javascript:JSInterface.ResizeWebView(document.body.scrollHeight)";
html += "};";
html += "</script>";**/
this.reactContext = reactContext;
layout = new CustomView(reactContext);
return layout;
}
@ReactProp(name = "messageId")
public void setMessageId(LinearLayout view, int messageId) {
layout.setMessageId(String.valueOf(messageId));
}
@ReactProp(name = "message")
public void setWebviewHtml(LinearLayout view, String html) {
String uniqueId = UUID.randomUUID().toString().replace("-", "");
uniqueId = "APPJS" + uniqueId;
//Toast.makeText(reactContext, "uniqueId: " + uniqueId, Toast.LENGTH_SHORT).show();
html = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>HTML5 Boilerplate</title><script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js' integrity='sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==' crossorigin='anonymous' referrerpolicy='no-referrer'></script></head><body style='margin:0;padding:0;word-wrap:break-word;'>" + html + "</body></html>";
//oast.makeText(reactContext, "html: " + html, Toast.LENGTH_SHORT).show();
html += "<script>";
html += "$(document).ready(function() {";
html += "javascript:" + uniqueId + ".ResizeWebView($(document).height())";
html += "});";
html += "</script>";
layout.setWebviewHtml(html, uniqueId);
}
@Override
public @Nullable Map getExportedCustomDirectEventTypeConstants() {
return MapBuilder.of("myCallback",
MapBuilder.of("registrationName", "myCallback"));
}
}
</code>
package com.poller;
import android.graphics.Color;
import android.view.ViewGroup.LayoutParams;
import android.text.Html;
import android.widget.TextView;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.opengl.GLSurfaceView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.views.text.ReactTextShadowNode;
import java.util.Map;
import java.util.UUID;
public class MyCustomViewManager extends SimpleViewManager<CustomView> {
public static final String REACT_CLASS = "MyCustomView";
CustomView layout;
WebView webView;
int h = 0;
int w = 0;
ThemedReactContext reactContext;
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected CustomView createViewInstance(ThemedReactContext reactContext) {
/**String html = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>HTML5 Boilerplate</title></head><body style='margin:0;padding:0;'><h1>Page Title 2</h1></body></html>";
html += "<script>";
html += "window.onload = function(){";
html += "javascript:JSInterface.ResizeWebView(document.body.scrollHeight)";
html += "};";
html += "</script>";**/
this.reactContext = reactContext;
layout = new CustomView(reactContext);
return layout;
}
@ReactProp(name = "messageId")
public void setMessageId(LinearLayout view, int messageId) {
layout.setMessageId(String.valueOf(messageId));
}
@ReactProp(name = "message")
public void setWebviewHtml(LinearLayout view, String html) {
String uniqueId = UUID.randomUUID().toString().replace("-", "");
uniqueId = "APPJS" + uniqueId;
//Toast.makeText(reactContext, "uniqueId: " + uniqueId, Toast.LENGTH_SHORT).show();
html = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>HTML5 Boilerplate</title><script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js' integrity='sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==' crossorigin='anonymous' referrerpolicy='no-referrer'></script></head><body style='margin:0;padding:0;word-wrap:break-word;'>" + html + "</body></html>";
//oast.makeText(reactContext, "html: " + html, Toast.LENGTH_SHORT).show();
html += "<script>";
html += "$(document).ready(function() {";
html += "javascript:" + uniqueId + ".ResizeWebView($(document).height())";
html += "});";
html += "</script>";
layout.setWebviewHtml(html, uniqueId);
}
@Override
public @Nullable Map getExportedCustomDirectEventTypeConstants() {
return MapBuilder.of("myCallback",
MapBuilder.of("registrationName", "myCallback"));
}
}
This is the CustomView:
<code> package com.poller;
import android.widget.LinearLayout;
import android.content.Context;
import android.webkit.WebView;
import android.widget.Toast;
import android.os.Bundle;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import android.view.View;
public class CustomView extends LinearLayout {
ViewTreeObserver viewTreeObserver;
public CustomView(Context context) {
super(context);//ADD THIS
//setContentView(R.layout.webview_layout);
inflate(context, R.layout.webview_layout, this);
//Toast.makeText(context, "html " + html, Toast.LENGTH_SHORT).show();
webView = (WebView) findViewById(R.id.webview);
public void setMessageId(String messageId) {
this.messageId = messageId;
public void setWebviewHtml(String html, String uniqueId) {
//Toast.makeText(context, "html2: " + html, Toast.LENGTH_SHORT).show();
webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSInterface(webView, context, this), uniqueId);
public void sendWebViewHeight(final float height){
WritableMap map = Arguments.createMap();
map.putString("messageId", String.valueOf(messageId));
map.putString("wVheight", String.valueOf(height));
final ReactContext context = (ReactContext) getContext();
context.getJSModule(RCTEventEmitter.class).receiveEvent(
<code> package com.poller;
import android.widget.LinearLayout;
import android.content.Context;
import android.webkit.WebView;
import android.widget.Toast;
import android.os.Bundle;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import android.view.View;
public class CustomView extends LinearLayout {
private Context context;
ViewTreeObserver viewTreeObserver;
WebView webView;
String messageId = "";
public CustomView(Context context) {
super(context);//ADD THIS
this.context = context;
//setContentView(R.layout.webview_layout);
inflate(context, R.layout.webview_layout, this);
//Toast.makeText(context, "html " + html, Toast.LENGTH_SHORT).show();
webView = (WebView) findViewById(R.id.webview);
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public void setWebviewHtml(String html, String uniqueId) {
//Toast.makeText(context, "html2: " + html, Toast.LENGTH_SHORT).show();
webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSInterface(webView, context, this), uniqueId);
}
public void sendWebViewHeight(final float height){
WritableMap map = Arguments.createMap();
map.putString("messageId", String.valueOf(messageId));
map.putString("wVheight", String.valueOf(height));
final ReactContext context = (ReactContext) getContext();
context.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
"myCallback",
map
);
}
}
</code>
package com.poller;
import android.widget.LinearLayout;
import android.content.Context;
import android.webkit.WebView;
import android.widget.Toast;
import android.os.Bundle;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import android.view.View;
public class CustomView extends LinearLayout {
private Context context;
ViewTreeObserver viewTreeObserver;
WebView webView;
String messageId = "";
public CustomView(Context context) {
super(context);//ADD THIS
this.context = context;
//setContentView(R.layout.webview_layout);
inflate(context, R.layout.webview_layout, this);
//Toast.makeText(context, "html " + html, Toast.LENGTH_SHORT).show();
webView = (WebView) findViewById(R.id.webview);
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public void setWebviewHtml(String html, String uniqueId) {
//Toast.makeText(context, "html2: " + html, Toast.LENGTH_SHORT).show();
webView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new JSInterface(webView, context, this), uniqueId);
}
public void sendWebViewHeight(final float height){
WritableMap map = Arguments.createMap();
map.putString("messageId", String.valueOf(messageId));
map.putString("wVheight", String.valueOf(height));
final ReactContext context = (ReactContext) getContext();
context.getJSModule(RCTEventEmitter.class).receiveEvent(
getId(),
"myCallback",
map
);
}
}
And this is my JavaScript Interface so that the WebView can talk to the Native Code:
<code> package com.poller;
import android.content.Context;
import android.webkit.WebView;
import android.widget.Toast;
import android.content.res.Resources;
import android.webkit.JavascriptInterface;
public class JSInterface{
private WebView mAppView;
public JSInterface (WebView appView, Context context, CustomView cv) {
public void ResizeWebView(final float height) {
float webViewHeight = height;//(height * context.getResources().getDisplayMetrics().density);
cv.sendWebViewHeight(webViewHeight);
//Toast.makeText(context, String.valueOf(webViewHeight), Toast.LENGTH_SHORT).show();
<code> package com.poller;
import android.content.Context;
import android.webkit.WebView;
import android.widget.Toast;
import android.content.res.Resources;
import android.webkit.JavascriptInterface;
public class JSInterface{
private WebView mAppView;
private Context context;
public CustomView cv;
public JSInterface (WebView appView, Context context, CustomView cv) {
this.mAppView = appView;
this.context = context;
this.cv = cv;
}
@JavascriptInterface
public void ResizeWebView(final float height) {
float webViewHeight = height;//(height * context.getResources().getDisplayMetrics().density);
cv.sendWebViewHeight(webViewHeight);
//Toast.makeText(context, String.valueOf(webViewHeight), Toast.LENGTH_SHORT).show();
}
}
</code>
package com.poller;
import android.content.Context;
import android.webkit.WebView;
import android.widget.Toast;
import android.content.res.Resources;
import android.webkit.JavascriptInterface;
public class JSInterface{
private WebView mAppView;
private Context context;
public CustomView cv;
public JSInterface (WebView appView, Context context, CustomView cv) {
this.mAppView = appView;
this.context = context;
this.cv = cv;
}
@JavascriptInterface
public void ResizeWebView(final float height) {
float webViewHeight = height;//(height * context.getResources().getDisplayMetrics().density);
cv.sendWebViewHeight(webViewHeight);
//Toast.makeText(context, String.valueOf(webViewHeight), Toast.LENGTH_SHORT).show();
}
}
In my React Native Component I import the MyCustomeView:
myCallback: PropTypes.func,
const MyCustomView = requireNativeComponent('MyCustomView', iface);
<code> const iface = {
name: 'PollChat',
propTypes: {
myCallback: PropTypes.func,
...ViewPropTypes,
},
};
const MyCustomView = requireNativeComponent('MyCustomView', iface);
</code>
const iface = {
name: 'PollChat',
propTypes: {
myCallback: PropTypes.func,
...ViewPropTypes,
},
};
const MyCustomView = requireNativeComponent('MyCustomView', iface);
I have uses Iface because I need to send back the height of the WebView, so a call-back is needed to set the Components height when the state updates in the React Native Component.
This is the Component’s that renders and talks to the Native UI Component:
<code><MyCustomView messageId={e["message"]["mess"].id} message={e["message"]["mess"].message} style={{flex:1, height:heightWV[index] ? heightWV[index].height : 0}} myCallback={setChatWebViewHeight}/>
<code><MyCustomView messageId={e["message"]["mess"].id} message={e["message"]["mess"].message} style={{flex:1, height:heightWV[index] ? heightWV[index].height : 0}} myCallback={setChatWebViewHeight}/>
</code>
<MyCustomView messageId={e["message"]["mess"].id} message={e["message"]["mess"].message} style={{flex:1, height:heightWV[index] ? heightWV[index].height : 0}} myCallback={setChatWebViewHeight}/>
And this is the callback where native code sends back the message id and the webviews height:
<code>const setChatWebViewHeight = (e) =>{
const hasMessage = messageId.find((messageIdArr) => messageIdArr === parseInt(e.nativeEvent.messageId));
//If message has already loaded then dont update its state
height: parseFloat(e.nativeEvent.wVheight),
messsageId: parseInt(e.nativeEvent.messageId)
console.log(e.nativeEvent.messageId);
console.log(e.nativeEvent.wVheight);
setMessageId(oldArray => [...oldArray, parseInt(e.nativeEvent.messageId)]);
setHeightWV(oldArray => [...oldArray, heightData]);
<code>const setChatWebViewHeight = (e) =>{
e.persist();
const hasMessage = messageId.find((messageIdArr) => messageIdArr === parseInt(e.nativeEvent.messageId));
//If message has already loaded then dont update its state
if(!hasMessage){
var heightData = {
height: parseFloat(e.nativeEvent.wVheight),
messsageId: parseInt(e.nativeEvent.messageId)
}
console.log(e.nativeEvent.messageId);
console.log(e.nativeEvent.wVheight);
setMessageId(oldArray => [...oldArray, parseInt(e.nativeEvent.messageId)]);
setHeightWV(oldArray => [...oldArray, heightData]);
}
}
</code>
const setChatWebViewHeight = (e) =>{
e.persist();
const hasMessage = messageId.find((messageIdArr) => messageIdArr === parseInt(e.nativeEvent.messageId));
//If message has already loaded then dont update its state
if(!hasMessage){
var heightData = {
height: parseFloat(e.nativeEvent.wVheight),
messsageId: parseInt(e.nativeEvent.messageId)
}
console.log(e.nativeEvent.messageId);
console.log(e.nativeEvent.wVheight);
setMessageId(oldArray => [...oldArray, parseInt(e.nativeEvent.messageId)]);
setHeightWV(oldArray => [...oldArray, heightData]);
}
}
This is the state that holds the height and message id’s:
<code>const [messageGlobalId, setMessageGlobalId] = useState([]);
const [heightWV, setHeightWV] = useState([]);
<code>const [messageGlobalId, setMessageGlobalId] = useState([]);
const [heightWV, setHeightWV] = useState([]);
</code>
const [messageGlobalId, setMessageGlobalId] = useState([]);
const [heightWV, setHeightWV] = useState([]);
The WebView layout xml:
<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000" />
<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<WebView
android:id="@+id/webview"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000" />
</LinearLayout>
</code>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<WebView
android:id="@+id/webview"
android:padding="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000" />
</LinearLayout>
Everything works but the problem is that the messages takes time to update the ui, I believe its because the app cant handle more than one message rendering the WebView’s.
My question is, is there a faster way of updating the ui? because with this code the ui takes 2 minutes to finally load just 11 messages.
Here is a 2-3 minute video of how the app is reacting to the state:
<code>https://jumpshare.com/s/7AgxFaXpq8XX4g0j4WDw
<code>https://jumpshare.com/s/7AgxFaXpq8XX4g0j4WDw
</code>
https://jumpshare.com/s/7AgxFaXpq8XX4g0j4WDw