| 1 | const React = window.React; |
| 2 | const ReactDOM = window.ReactDOM; |
| 3 | |
| 4 | class IframePortal extends React.Component { |
| 5 | iframeRef = null; |
| 6 | |
| 7 | handleRef = ref => { |
| 8 | if (ref !== this.iframeRef) { |
| 9 | this.iframeRef = ref; |
| 10 | if (ref) { |
| 11 | if (ref.contentDocument && this.props.head) { |
| 12 | ref.contentDocument.head.innerHTML = this.props.head; |
| 13 | } |
| 14 | // Re-render must take place in the next tick (Firefox) |
| 15 | setTimeout(() => { |
| 16 | this.forceUpdate(); |
| 17 | }); |
| 18 | } |
| 19 | } |
| 20 | }; |
| 21 | |
| 22 | render() { |
| 23 | const ref = this.iframeRef; |
| 24 | let portal = null; |
| 25 | if (ref && ref.contentDocument) { |
| 26 | portal = ReactDOM.createPortal( |
| 27 | this.props.children, |
| 28 | ref.contentDocument.body |
| 29 | ); |
| 30 | } |
| 31 | |
| 32 | return ( |
| 33 | <div> |
| 34 | <iframe |
| 35 | title="Iframe portal" |
| 36 | style={{border: 'none', height: this.props.height}} |
| 37 | ref={this.handleRef} |
| 38 | /> |
| 39 | {portal} |
| 40 | </div> |
| 41 | ); |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | class IframeSubtree extends React.Component { |
| 46 | warned = false; |
| 47 | render() { |
| 48 | if (!this.warned) { |
| 49 | console.error( |
| 50 | `IFrame has not yet been implemented for React v${React.version}` |
| 51 | ); |
| 52 | this.warned = true; |
| 53 | } |
| 54 | return <div>{this.props.children}</div>; |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | export default ReactDOM.createPortal ? IframePortal : IframeSubtree; |