Last active
October 4, 2018 21:54
-
-
Save mattheu/38aaa1ea6aa29b27655cd08ff51020cd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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