Description:
The react-iframe component provides a simple way to embed another React app or component in an iframe. This opens up powerful possibilities for composition, security, and isolation of components.
How to use it:
1. Install and import the component into your React application.
# NPM $ npm i @uiw/react-iframe
import React from 'react'; import IFrame from '@uiw/react-iframe';
2. This is a quick example to demonstrate how you can wrap content within the ‘react-iframe’ component:
export default function Demo() {
return (
<IFrame>
any content here
</IFrame>
);
}3. The initialContent prop specifies the initial HTML to be injected into the frame. Note: This only happens once and won’t update even if the prop changes. By default, it is:
<!DOCTYPE html><html><head></head><body></body></html>
4. Use the mountTarget attribute (a CSS selector like #target/.target) to specify where within the iframe’s initial content your component should mount.
export default function Demo() {
return (
<IFrame initialContent={initialContent} mountTarget="#mountHere">
<div style={{ color: 'red' }}>ReactScript</div>
</IFrame>
);
}5. The ref Prop is your key to accessing the inner <iframe> DOM node directly.
import React, { useEffect, useState, Fragment } from 'react';
import IFrame from '@uiw/react-iframe';
export default function Demo() {
const [iframeRef, setIframeRef] = useState();
const [count, setCount] = useState(0);
useEffect(() => {
if (iframeRef) {
iframeRef.focus();
}
}, [iframeRef]);
const click = () => setCount(count + 1);
return (
<Fragment>
<button onClick={click} style={{ display: 'flex' }}>Click</button>
<IFrame ref={(node) => node && setIframeRef(node)}>
<div>Hello World!</div>
<div style={{ fontSize: 32, color: 'red' }}>{count}</div>
</IFrame>
</Fragment>
);
}6. Need to display a specific URL within the <iframe>? Just use the src prop.
import React, { useEffect, useState, Fragment } from 'react';
import IFrame from '@uiw/react-iframe';
export default function Demo() {
return (
<IFrame src="https://reactscript.com/" />
);
}7. Access the iframe’s window and document with ease using either the FrameContext.Consumer or the useFrame hook.
import React, { useEffect, useState, Fragment } from 'react';
import IFrame, { FrameContext } from '@uiw/react-iframe';
export default function Demo() {
return (
<IFrame>
<FrameContext.Consumer>
{({ document, window }) => {
return (
<div>
<div>Hello World!</div>
</div>
)
}}
</FrameContext.Consumer>
</IFrame>
);
}8. You can add content before the children of the frame using the head prop.
const head = (
// ...
);
export default function Demo() {
return (
<IFrame head={head}>
...
</IFrame>
);
}



