Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Iframe in react native?

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.

like image 514
Mengseng Oeng Avatar asked Oct 20 '18 15:10

Mengseng Oeng


People also ask

How do I use iframe in React?

In React, developers use iframes to create either a sandboxed component or an application that is isolated from its parent component. In an iframe, when a piece of content is embedded from an external source, it is completely controlled by the source instead of the website it is embedded in.

How do I embed in React Native?

You first get HTML embed codes from our oEmbed or Iframely API endpoints. Then you put those HTML codes as the source property of WebView component of React Native framework. Plus, inject a simple JavaScript that sends a message to the parent to change the height of the WebView once the embed codes unfurl themselves.

How do I set the iframe content of a React component?

To set the content of an iframe of a React component, we can set the srcDoc prop of the iframe element. to set the srcDoc prop to the HTML string that we want to display as the iframe's content. Therefore, we should see 'Hello World' displayed inside the iframe.


1 Answers

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>

Notes:

1) 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.

2) known issues about iframes and rn-webview:

https://github.com/react-native-webview/react-native-webview/issues?q=iframe+is%3Aopen

3) Link to snack:

https://snack.expo.dev/@florindobre99/webview-example

More info about webview here:

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

like image 59
Florin Dobre Avatar answered Oct 14 '22 01:10

Florin Dobre