Created
April 28, 2015 12:52
-
-
Save kenwheeler/8f7e5916b54c70fa454b to your computer and use it in GitHub Desktop.
webpack config
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 React = require('react/addons'); | |
var babel = require('babel'); | |
var selfCleaningTimeout = { | |
componentDidUpdate: function() { | |
clearTimeout(this.timeoutID); | |
}, | |
setTimeout: function() { | |
clearTimeout(this.timeoutID); | |
this.timeoutID = setTimeout.apply(null, arguments); | |
} | |
}; | |
var ComponentPreview = React.createClass({ | |
propTypes: { | |
code: React.PropTypes.string.isRequired | |
}, | |
mixins: [selfCleaningTimeout], | |
render: function() { | |
return <div ref="mount" />; | |
}, | |
componentDidMount: function() { | |
this.executeCode(); | |
}, | |
componentDidUpdate: function(prevProps) { | |
// execute code only when the state's not being updated by switching tab | |
// this avoids re-displaying the error, which comes after a certain delay | |
if (this.props.code !== prevProps.code) { | |
this.executeCode(); | |
} | |
}, | |
compileCode: function() { | |
return babel.transform( | |
'(function() {' + | |
this.props.code + | |
'\n})();', | |
{ stage: 1 } | |
).code; | |
}, | |
executeCode: function() { | |
var mountNode = this.refs.mount.getDOMNode(); | |
try { | |
React.unmountComponentAtNode(mountNode); | |
} catch (e) { } | |
try { | |
var compiledCode = this.compileCode(); | |
React.render(eval(compiledCode), mountNode); | |
} catch (err) { | |
this.setTimeout(function() { | |
React.render( | |
<div className="playgroundError">{err.toString()}</div>, | |
mountNode | |
); | |
}, 500); | |
} | |
} | |
}); | |
module.exports = ComponentPreview; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment