Created
January 30, 2017 02:27
-
-
Save raidenz/5b8286e4ab45b62890940e37c9724ba0 to your computer and use it in GitHub Desktop.
react embed gist
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
var EmbeddedGist = React.createClass({ | |
propTypes: { | |
gist: React.PropTypes.string.isRequired, // e.g. "username/id" | |
file: React.PropTypes.string // to embed a single specific file from the gist | |
}, | |
statics: { | |
// Each time we request a Gist, we'll need to generate a new | |
// global function name to serve as the JSONP callback. | |
gistCallbackId: 0, | |
nextGistCallback: function() { | |
return "embed_gist_callback_" + EmbeddedGist.gistCallbackId++; | |
}, | |
// The Gist JSON data includes a stylesheet to add to the page | |
// to make it look correct. `addStylesheet` ensures we only add | |
// the stylesheet one time. | |
stylesheetAdded: false, | |
addStylesheet: function(href) { | |
if (!EmbeddedGist.stylesheetAdded) { | |
EmbeddedGist.stylesheetAdded = true; | |
var link = document.createElement('link'); | |
link.type = "text/css"; | |
link.rel = "stylesheet"; | |
link.href = href; | |
document.head.appendChild(link); | |
} | |
} | |
}, | |
getInitialState: function() { | |
return { | |
loading: true, | |
src: "" | |
}; | |
}, | |
componentDidMount: function() { | |
// Create a JSONP callback that will set our state | |
// with the data that comes back from the Gist site | |
var gistCallback = EmbeddedGist.nextGistCallback(); | |
window[gistCallback] = function(gist) { | |
if (this.isMounted()) { | |
this.setState({ | |
loading: false, | |
src: gist.div | |
}); | |
EmbeddedGist.addStylesheet(gist.stylesheet); | |
} | |
}.bind(this); | |
var url = "https://gist.github.com/" + this.props.gist + ".json?callback=" + gistCallback; | |
if (this.props.file) { | |
url += "&file=" + this.props.file; | |
} | |
// Add the JSONP script tag to the document. | |
var script = document.createElement('script'); | |
script.type = 'text/javascript'; | |
script.src = url; | |
document.head.appendChild(script); | |
}, | |
render() { | |
if (this.state.loading) { | |
return <div>loading...</div>; | |
} else { | |
return <div dangerouslySetInnerHTML={{__html: this.state.src}} />; | |
} | |
} | |
}); |
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
var app = ( | |
<div> | |
<EmbeddedGist gist="BinaryMuse/a57ae1a551472e06b29a" file="restful.js" /> | |
<hr /> | |
<EmbeddedGist gist="BinaryMuse/bb9f2cbf692e6cfa4841" /> | |
</div> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment