How to use Iframe in react native?

Mengseng Oeng picture Mengseng Oeng · Oct 20, 2018 · Viewed 19.8k times · Source

I try to find any way to add Iframe to my react native app. I found react-iframe, but it didn't work for me. I followed document. I just import react-iframe and copy Iframe tag to use. My result is like image below. enter image description here

I need other way to use Iframe in react native app. Thank you.

Answer

Florin Dobre picture Florin Dobre · Oct 21, 2018

Try to use react-native-webview:

import { WebView } from 'react-native-webview';

....

<WebView
          scalesPageToFit={true}
          bounces={false}
          javaScriptEnabled
          style={{ height: 500, width: 300 }}
          source={{
            html: `
                  <!DOCTYPE html>
                  <html>
                    <head></head> // <--add header styles if needed
                    <body>
                      <div id="baseDiv">${iframeString}</div> //<--- add your iframe here
                    </body>
                  </html>
            `,
          }}
          automaticallyAdjustContentInsets={false}
        />

You can use an iframeString value like:

<iframe src="https://mdn-samples.mozilla.org/snippets/html/iframe-simple-contents.html"
            title="iframe Example 1" width="400" height="300">
</iframe>

Note: since source.html param can be any html string you could also pass the iframeString directly without any html page wrapper. In my cases I found it's easier to customize the displayed content with that outer html wrapper code.

More info about webview here:

https://github.com/react-native-community/react-native-webview