Skip to content

Instantly share code, notes, and snippets.

@msmfsd

msmfsd/Iframe.js

Last active Jul 15, 2020
Embed
What would you like to do?
React iframe component
/*
INIT: ensure Babel/Eslint/Flow is configured for ES Class Fields & Static Properties
JSX USAGE: <Iframe src='http://web.site' onLoad={myOnloadFunction}/>
*/
import React, { Component, PropTypes } from 'react'
import ReactDOM from 'react-dom'
class Iframe extends Component {
static propTypes: Object = {
src: PropTypes.string.isRequired,
onLoad: PropTypes.func,
}
componentDidMount () {
let iframe = ReactDOM.findDOMNode(this.refs.iframe)
iframe.addEventListener('load', this.props.onLoad);
}
render () {
const iframeStyle = {
width: '100%',
height: '100%',
border: '0',
position: 'absolute',
}
return (
<iframe
ref="iframe"
{...this.props}
frameBorder={'0'}
width={'100%'}
height={'100%'}
style={iframeStyle}
/>
)
}
}
export default Iframe
@srdjanRakic

This comment has been minimized.

Copy link

@srdjanRakic srdjanRakic commented May 11, 2018

Hi Morris, thank you for your gist.
Would you mind telling me what does the load function do?

Thanks in advance.

@xbojch

This comment has been minimized.

Copy link

@xbojch xbojch commented May 25, 2018

@srdjanRakic it lets you pass in a callback that gets called when the content in the iframe is loaded.

@shyam-habarakada

This comment has been minimized.

Copy link

@shyam-habarakada shyam-habarakada commented May 29, 2018

Shouldn't this implement,

shouldComponentUpdate () {
 return false;
}

... per this post ?

@lmaddio

This comment has been minimized.

Copy link

@lmaddio lmaddio commented Jun 5, 2018

What about removing listener when unmounting the component?

@momendo

This comment has been minimized.

Copy link

@momendo momendo commented Jan 3, 2019

componentDidMount () {
  let iframe = ReactDOM.findDOMNode(this.refs.iframe)
  // iframe.addEventListener('load', this.props.onLoad); // BUG this fires twice in Chrome
  iframe.onload = () => this.props.onLoad // this event fires once
}

componentWillUnmount() {
  let iframe = ReactDOM.findDOMNode(this.refs.iframe)
  //iframe.removeEventListener('load');
  iframe.onload = null // destroy event handler
}
@smokinjoe

This comment has been minimized.

Copy link

@smokinjoe smokinjoe commented Jan 22, 2019

@momendo unfortunately with typescript I'm constantly getting this error with your solution:

[dev:build]         TS2339: Property 'load' does not exist on type 'Element | Text'.
[dev:build]       Property 'load' does not exist on type 'Element'.
@albanx

This comment has been minimized.

Copy link

@albanx albanx commented May 4, 2019

Iframe in react has a problem, if you need to destroy it, for example because you load some js inside it, and want to load a new JS, you cannot do that with react.

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