5

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> 
Prakul Gupta
  • 51
  • 1
  • 2

3 Answers3

6

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.

Rémi Doreau
  • 232
  • 2
  • 8
  • 1
    Thanks @rémi-doreau this does render the react component .. following to the above approach you suggested..if the react component inside uses document object and appends a script..how will this gonna work? Do you have any idea ? As document object will not be available for react-native app. – Prakul Gupta Jun 01 '20 at 17:13
  • Is it possible to pass props to the ``? – Trevor Feb 18 '21 at 17:50
  • Did you manage to do it with complex react components? that receive props, uses state management, etc? I'm facing the same issue with the need of loading a big and complex sub-tree of a bigger react component @Trevor – jizanthapus Oct 06 '22 at 10:27
  • Please if any one finds solution give me a suggestion I had try this, but I got error "Property 'TextEncoder' doesn't exist, js engine: hermes" & " Metro (the local dev server) is run from the wrong folder" and "A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called., js engine: hermes" – siddharth Alagesan Mar 19 '23 at 14:54
-1

if you want to load HTML directly, you can use the html property in WebView’s source property, as shown below:

<WebView
  originWhitelist={['*']}
  source={{ html: '<h1>Hello world</h1>' }}
/>

for more details of react-native-web-view you can learn from here

https://blog.logrocket.com/the-complete-guide-to-react-native-webview/

https://github.com/react-native-community/react-native-webview/blob/master/docs/Reference.md

Shahid ali
  • 246
  • 2
  • 5
-1

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.

Luca Fabbian
  • 194
  • 6