Last active
August 29, 2015 14:17
-
-
Save cahnory/40a330c1d833bdc87af0 to your computer and use it in GitHub Desktop.
Load and render react component from browser
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
/*jslint node: true */ | |
'use strict'; | |
var React = require('react'); | |
var loader = require('scriptjs'); | |
module.exports = React.createClass({ | |
propTypes: { | |
handler: React.PropTypes.string.isRequired, | |
handlerUrl: React.PropTypes.string, | |
preloader: React.PropTypes.element, | |
props: React.PropTypes.object | |
}, | |
getInitialState: function () { | |
return { | |
resolved: false, | |
}; | |
}, | |
componentDidMount: function () { | |
// load component file | |
loader(this.props.handlerUrl || this.props.handler, this.props.handler) | |
.ready(this.props.handler, function() { | |
this.setState({ | |
resolved: require(this.props.handler) | |
}); | |
}.bind(this)); | |
}, | |
render: function () { | |
var Handler; | |
// render component if resolved | |
if (this.state.resolved) { | |
Handler = this.state.resolved; | |
// or preloader if defined | |
} else if (this.props.preloader) { | |
Handler = this.props.preloader; | |
} | |
if (Handler) { | |
return <Handler {...this.props} />; | |
} else { | |
// default preloader | |
return <div>Component is loading…</div>; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment