Skip to content

Change messaging API #176

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@ The communication between React app and React Native app will be also simplified
- All JS modules (with or without JSX/TypeScript) will be bundled with [esbuild](https://github.com/evanw/esbuild).
- **NOTE: Only the edits in the entry file of web will invoke rebuild because of the limitation of [metro](https://github.com/facebook/metro)'s build process.**
- Handle communication between React Native and WebView with React hook style
- With `useWebViewMessage` hook, you can subscribe messages from WebView.
- With `useNativeMessage` hook, you can subscribe messages from React Native.
- `emit` function sends message.
- With `useWebViewMessage` hook, you can subscribe messages from WebView sent with `emitToWebView`.
- With `useNativeMessage` hook, you can subscribe messages from React Native sent with `emitToNative`.
- Support bundling some assets in web side with [ES6 import syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
- `.json` is imported as an object, like require in Node.js.
- `.txt` and `.md` are imported as string, like [raw-loader](https://github.com/webpack-contrib/raw-loader).
Expand Down Expand Up @@ -157,7 +156,7 @@ module.exports = (async () => {
import React, { useState } from "react";
import {
webViewRender,
emit,
emitToNative,
useNativeMessage,
} from "react-native-react-bridge/lib/web";
// Importing css is supported
Expand All @@ -179,10 +178,10 @@ const Root = () => {
<div>{data}</div>
<button
onClick={() => {
// emit sends message to React Native
// emitToNative sends message to React Native
// type: event name
// data: some data which will be serialized by JSON.stringify
emit({ type: "hello", data: 123 });
emitToNative({ type: "hello", data: 123 });
}}
/>
</div>
Expand All @@ -201,18 +200,19 @@ export default webViewRender(<Root />);

import React from "react";
import WebView from "react-native-webview";
import { useWebViewMessage } from "react-native-react-bridge";
import { emitToWebView, useWebViewMessage } from "react-native-react-bridge";
import webApp from "./WebApp";

const App = () => {
const ref = useRef(null);
// useWebViewMessage hook create props for WebView and handle communication
// The argument is callback to receive message from React
const { ref, onMessage, emit } = useWebViewMessage((message) => {
// emit sends message to React
const onMessage = useWebViewMessage((message) => {
// emitToWebView sends message to React
// type: event name
// data: some data which will be serialized by JSON.stringify
if (message.type === "hello" && message.data === 123) {
emit({ type: "success", data: "succeeded!" });
emitToWebView(ref, { type: "success", data: "succeeded!" });
}
});

Expand Down

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions examples/DempApp/WebApp/index.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, {useState} from 'react';
import {
webViewRender,
emit,
emitToNative,
useNativeMessage,
} from 'react-native-react-bridge/lib/web';
import './example.css';
Expand Down Expand Up @@ -29,7 +29,7 @@ const Root = () => {
</div>
<textarea value={data} onChange={e => setData(e.target.value)} />
<div>
<Button onClick={() => emit({type: 'hi', data: data})}>
<Button onClick={() => emitToNative({type: 'hi', data: data})}>
send to React Native
</Button>
</div>
Expand Down
9 changes: 5 additions & 4 deletions examples/DempApp/app/(tabs)/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useRef, useState } from "react";
import {
SafeAreaView,
StyleSheet,
Expand All @@ -8,12 +8,13 @@ import {
TextInput,
} from "react-native";
import WebView from "react-native-webview";
import { useWebViewMessage } from "react-native-react-bridge";
import { emitToWebView, useWebViewMessage } from "react-native-react-bridge";
import webApp from "../../WebApp";

const App = () => {
const [data, setData] = useState("This is React Native");
const { ref, onMessage, emit } = useWebViewMessage((message) => {
const ref = useRef<WebView>(null);
const onMessage = useWebViewMessage<string>((message) => {
if (message.type === "hi") {
setData(message.data);
}
Expand All @@ -36,7 +37,7 @@ const App = () => {
value={data}
/>
<Pressable
onPress={() => emit({ type: "hello", data: data })}
onPress={() => emitToWebView(ref, { type: "hello", data: data })}
style={styles.button}
>
<Text>send to Web</Text>
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
* @module
*/
export type { ReactNativeMessage, WebViewMessage } from "./types";
export { useWebViewMessage } from "./native";
export { useWebViewMessage, emitToWebView } from "./native";
26 changes: 14 additions & 12 deletions src/native/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useRef } from "react";
import { RefObject, useCallback } from "react";
import type WebView from "react-native-webview";
import type { WebViewMessageEvent, WebViewProps } from "react-native-webview";
import { TO_WEB_EVENT_KEY } from "../constants";
Expand Down Expand Up @@ -28,23 +28,25 @@ export const buildEmitToWebView = <T>(
export const useWebViewMessage = <T>(
onSubscribe: (message: WebViewMessage<T>) => void
) => {
const ref = useRef<WebView>(null);
const onMessage: WebViewProps["onMessage"] = useCallback(
(event: WebViewMessageEvent) => {
return useCallback(
((event: WebViewMessageEvent) => {
try {
const res = JSON.parse(event.nativeEvent.data);
onSubscribe({ type: res.type, data: res.data });
} catch (e) {
// NOP
}
},
}) satisfies WebViewProps["onMessage"],
[onSubscribe]
);
const emit = useCallback(
(message: ReactNativeMessage<T>) => {
ref.current?.injectJavaScript(buildEmitToWebView(message));
},
[ref]
);
return { ref, onMessage, emit };
};

/**
* A function to send a message to WebView.
*/
export const emitToWebView = <T>(
ref: RefObject<WebView>,
message: ReactNativeMessage<T>
) => {
ref.current?.injectJavaScript(buildEmitToWebView(message));
};
2 changes: 1 addition & 1 deletion src/web/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const getWebViewRootElement = (): HTMLElement =>
document.getElementById(WEB_ROOT_ID)!;

/**
* A function to send a message to React Native
* A function to send a message to React Native.
*/
export const emitToNative = <T>(message: WebViewMessage<T>) => {
(window as any).ReactNativeWebView.postMessage(JSON.stringify(message));
Expand Down
8 changes: 6 additions & 2 deletions src/web/preact.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
*/
import { useEffect } from "preact/compat";
import { render, ComponentChild } from "preact";
import { listenNativeMessage, emitToNative, getWebViewRootElement } from "./core";
import {
listenNativeMessage,
emitToNative,
getWebViewRootElement,
} from "./core";
import type { ReactNativeMessage } from "../types";

/**
Expand All @@ -28,4 +32,4 @@ export const useNativeMessage = <T>(
useEffect(() => listenNativeMessage(onSubscribe), [onSubscribe]);
};

export { emitToNative as emit };
export { emitToNative };
6 changes: 3 additions & 3 deletions src/web/react.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it } from "vitest";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import { useNativeMessage, emit } from "./react";
import { useNativeMessage, emitToNative } from "./react";
import { useWebViewMessage, buildEmitToWebView } from "../native";
import { useEffect, useState } from "react";
import { ReactNativeMessage, WebViewMessage } from "../types";
Expand Down Expand Up @@ -88,7 +88,7 @@ describe("send message to native", () => {
return (
<button
onClick={() => {
emit(message);
emitToNative(message);
}}
>
send
Expand All @@ -98,7 +98,7 @@ describe("send message to native", () => {
const NativeApp = ({ target }: { target: string }) => {
const [data, setData] = useState<null | string>(null);
const [count, setCount] = useState(0);
const { onMessage } = useWebViewMessage<string>((m) => {
const onMessage = useWebViewMessage<string>((m) => {
if (m.type === target) {
setData(m.data);
}
Expand Down
8 changes: 6 additions & 2 deletions src/web/react.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@
import { ReactElement, useEffect } from "react";
import { render } from "react-dom";
import { createRoot } from "react-dom/client";
import { emitToNative, getWebViewRootElement, listenNativeMessage } from "./core";
import {
emitToNative,
getWebViewRootElement,
listenNativeMessage,
} from "./core";
import type { ReactNativeMessage } from "../types";

/**
Expand Down Expand Up @@ -37,4 +41,4 @@ export const useNativeMessage = <T>(
useEffect(() => listenNativeMessage(onSubscribe), [onSubscribe]);
};

export { emitToNative as emit };
export { emitToNative };