Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@grese
Created June 12, 2016 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grese/a7d9ee5ec5534583572ad232a82e24d8 to your computer and use it in GitHub Desktop.
Save grese/a7d9ee5ec5534583572ad232a82e24d8 to your computer and use it in GitHub Desktop.
A ReactJS component for rendering other React components into a "src-less" iframe
var Sandboxr = React.createClass({
componentDidMount() {
const iframe = this.refs.frame;
const node = iframe.contentDocument.createElement('div');
iframe.contentDocument.body.appendChild(node);
this._contentNode = node;
this._renderChildrenIntoContentNode(this.props);
},
_renderChildrenIntoContentNode(props) {
ReactDOM.unstable_renderSubtreeIntoContainer(
this,
<div>{props.children}</div>,
this._contentNode
);
},
componentWillUpdate(nextProps) {
this._renderChildrenIntoContentNode(nextProps);
},
componentWillUnmount() {
ReactDOM.unmountComponentAtNode(this._contentNode);
},
render() {
return <iframe
ref="frame"
width={this.props.width}
height={this.props.height}
/>;
}
});
var Sample = React.createClass({
render() {
return <div>{this.props.text}</div>;
}
});
ReactDOM.render(
<Sandboxr width="250" height="250">
<Sample text="Hello world!" />
<Sample text="It's nice to see you again :P" />
</Sandboxr>,
document.getElementById('container')
);
@grese
Copy link
Author

grese commented Jun 12, 2016

This is a sample of how one can render React components into an iframe. This can be useful for sandboxing styles/markup from other places.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment