Skip to content

Instantly share code, notes, and snippets.

@mattheu
Last active October 4, 2018 21:54
Show Gist options
  • Save mattheu/38aaa1ea6aa29b27655cd08ff51020cd to your computer and use it in GitHub Desktop.
Save mattheu/38aaa1ea6aa29b27655cd08ff51020cd to your computer and use it in GitHub Desktop.
/* global wp */
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'proptypes';
const { Component } = wp.element;
class Iframe extends Component {
propTypes = {
frameProps: PropTypes.object,
scripts: PropTypes.array,
};
defaultProps = {
scripts: [],
frameProps: {
frameBorder: 0,
},
};
constructor( props ) {
super( props );
const d = new Date();
this.time = d.toString();
}
render() {
return (
<iframe
{ ...this.props.frameProps }
data-test={ this.time }
/>
);
}
componentDidMount() {
const frameBody = ReactDOM.findDOMNode( this ).contentDocument.body;
const el = document.createElement( 'div' );
frameBody.appendChild( el );
this.el = el;
this.updateIFrameContents();
window.setTimeout( () => {
this.loadScripts();
}, 1000 );
}
componentDidUpdate() {
this.updateIFrameContents();
}
updateIFrameContents() {
const { children } = this.props;
ReactDOM.render( <div>{ children }</div>, this.el );
}
loadScripts() {
const { scripts } = this.props;
const frameBody = ReactDOM.findDOMNode( this ).contentDocument.body;
scripts.forEach( script => {
const scriptEl = document.createElement( 'script' );
scriptEl.src = script.src;
Object.keys( script.data ).forEach( prop => scriptEl.dataset[ prop ] = script.data[ prop ] );
frameBody.appendChild( scriptEl );
} );
}
}
export default Iframe;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment