Created
January 7, 2015 16:43
-
-
Save iest/3b571a6ddcdd9ddab3cf to your computer and use it in GitHub Desktop.
Basic react iframe with onLoad handler
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
'use strict'; | |
var React = require('react'); | |
var BzIframe = React.createClass({ | |
propTypes: { | |
src: React.PropTypes.string.isRequired, | |
onLoad: React.PropTypes.func | |
}, | |
componentDidMount: function() { | |
this.refs.iframe.getDOMNode().addEventListener('load', this.props.onLoad); | |
}, | |
render: function() { | |
return <iframe ref="iframe" {...this.props}/>; | |
} | |
}); | |
module.exports = BzIframe; |
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
var Example = React.createClass({ | |
getInitialState: function() { | |
return { | |
isLoading: true | |
}; | |
}, | |
render: function() { | |
var classes = cx({ | |
'is-loading': this.state.isLoading // Hide `is-loading` with CSS | |
}); | |
return ( | |
{this.state.isLoading ? | |
<p>Loading... A spinner would probably be nice here</p> | |
:null | |
} | |
<BzIframe className={classes} onLoad={this._iframeLoaded} src="http://link-to-somewhere"/> | |
</div> | |
</DocumentTitle> | |
); | |
}, | |
_iframeLoaded: function() { | |
this.setState({ | |
isLoading: false | |
}); | |
} | |
}); |
Thanks, though I am having some difficulties in how to use this in my react app.. Say I pass an url into the src of the BzIframe, (and thus into the iframe), which in turn renders that webpage in the iframe, and when the iframe-url is changed, for example by the user clicking a button and getting redirected..how would I be able to get that redirct-url back into my react app?
Thanks!
What if Ifram failed to load the URL?
I would like to see how we can handle when the url
don't resolve or fails to load?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
+1 on @kocur4d, @iest there are breaking changes to recent versions of React that would cause this code to throw errors. Thank you very much for providing a clear example on how to harness iframe onload in React!