Created
October 13, 2016 09:49
-
-
Save nihaux/e0a7eee88725a3defd7f1400dca8362b to your computer and use it in GitHub Desktop.
This file contains 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
import React from 'react'; | |
class EmbedIframe extends React.Component { | |
resizeIframe = () => { | |
const height = Math.max(this.props.minHeight, this.iframe.contentWindow.document.body.offsetHeight); | |
this.iframe.height = `${height}px`; | |
} | |
componentDidMount = () => { | |
const html = this.props.html; | |
const page = ` | |
<html> | |
<body style="margin:0;padding:0"> | |
${this.props.html} | |
</body> | |
</html> | |
`; | |
this.iframe.addEventListener('load', () => { | |
this.resizeIframe(); | |
const config = { | |
attributes: true, | |
attributeOldValue: false, | |
characterData: true, | |
characterDataOldValue: false, | |
childList: true, | |
subtree: true | |
}; | |
const observer = new MutationObserver(this.resizeIframe); | |
observer.observe(this.iframe.contentWindow.document.body, config); | |
}); | |
this.iframe.contentWindow.document.open('text/html', 'replace'); | |
this.iframe.contentWindow.document.write(page); | |
this.iframe.contentWindow.document.close(); | |
} | |
render = () => ( | |
<iframe | |
ref={(i) => { this.iframe = i; }} | |
src="about:blank" | |
width={this.props.width} | |
height={`${this.props.minHeight}px`} | |
scrolling="no" | |
frameBorder="0" | |
/> | |
); | |
} | |
EmbedIframe.propTypes = { | |
width: React.PropTypes.string, | |
minHeight: React.PropTypes.int, | |
html: React.PropTypes.string.required, | |
}; | |
EmbedIframe.defaultProps = { | |
minHeight: 50, | |
width: '100%', | |
}; | |
export default EmbedIframe; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment