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.
I need other way to use Iframe in react native app. Thank you.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With