How to inject React Component inside WebView (react-native-webview)?

Viewed 3109

Is there a way to pass in a web React component to WebView directly? Something like this-

import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView
        source={{ html: "<ReactContainer/>" }}
></WebView> 
3 Answers

You can render a React component to its initial HTML with renderToString() and then display it inside your WebView like so:

import { renderToString } from 'react-dom/server'
import ReactContainer from 'somewhere';
import { WebView } from "react-native-webview";

<WebView source={{ html: renderToString(<ReactContainer />) }}></WebView>;


More infos about ReactDOMServer here.

No, there is not. React.js and React native shares the same syntax but are really different framework: they follow different rules and are build in a different way. Inside a webview, there is no react framework avaiable or runtime (unless you import React.js as a <script> tag as a website would).

However, as some other answer pointed, you can use renderToString() and it will work in some situations (it just precompile your component, it does not provide exactly what you want) - it's more a hack than a solution.

Related