Vardan
Vardan

Reputation: 75

Embed React web application into React Native WebView

I have a monorepo where I have web and mobile apps (React and React Native respectively) and want to embed the web app into the mobile using React Native WebView.

I read in docs that WebView source can be either file URL or static HTML page, so it expects the passed source to be something like this:

<WebView source={{ uri: 'https://my-web-app/' }} />

But what I have is only web app's dist/ folder. Is there a way to pass app.js and app.css from the dist/* folder into WebView?

I'm also assuming that maybe Metro bundler could create some HTML page using those files and then that page would be passed to the WebView, but not quite sure if that's possible.

Upvotes: 2

Views: 4813

Answers (1)

Vardan
Vardan

Reputation: 75

So I followed the way suggested here, which is the short version of this article.

What I did is basically the following:

  1. Created html/Web.bundle/src/web-src folder in mobile
  2. Put all css and js files into html/Web.bundle/src/index.html file, which roughly looks like this:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta content="IE=edge" http-equiv="X-UA-Compatible" />
    <meta content="width=device-width, initial-scale=1" name="viewport" />
    <link rel="stylesheet" href="web-src/app.css" />
  </head>

  <body>
    <script src="web-src/app.js"></script>
  </body>
</html>
  1. Created WebViewRenderer.tsx file that renders the WebView, and provided the index.html file as a source of the WebView:
const WebViewRenderer = () => {
  const sourceUri = (Platform.OS === 'android' ? 'file:///android_asset/' : '') + 'Web.bundle/index.html'

  return (
    <WebView
      source={{ uri: sourceUri }}
      originWhitelist={['*']}
      onLoad={() => console.log('Loaded')}
      onError={() => console.error('An error has occurred')}
      onHttpError={() => console.error('An HTTP error has occurred')}
      onMessage={(msg) => console.log('Got a message', msg)}
      javaScriptEnabled={true}
      allowFileAccess={true}
      injectedJavaScript={injectedJS}
    />
  )
}

That's it - now the web content is rendered in the WebView.

I'd recommend to have a look at the original article, since it explains everything in more detail, and also contains important information about configs and edge cases (such as passing the query params from mobile to web).

Upvotes: 0

Related Questions