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> 

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Is it possible to pass props to the <ReactContainer />?
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
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"
-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.

Comments

-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.