Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save whoisryosuke/17d79b09a4923546ab58009720d50976 to your computer and use it in GitHub Desktop.
Save whoisryosuke/17d79b09a4923546ab58009720d50976 to your computer and use it in GitHub Desktop.
ReactJS / GatsbyJS - Add a Codepen script to your blog posts. To see Codepens show in your posts, add the embed code into your Markdown files without the external Codepen JS script. Make sure to add this to the component you use to `createPage()` blog posts in `gatsby-node.js`
export default class BlogPost extends Component {
constructor(props) {
super(props);
this.state = {
'codepen': false
};
}
componentDidMount() {
// Add Codepen script to <body> if we detect a Codepen embed
const codepen = document.getElementsByClassName('codepen');
if (codepen.length > 0) {
// Check if we've already embedded the script
if (!document.getElementById('codepen-script') || !this.state.codepen) {
// Create script element with Codepen embed JS lib
const s = document.createElement('script')
s.async = s.defer = true
s.src = `//static.codepen.io/assets/embed/ei.js`
s.id = 'codepen-script'
const body: HTMLElement | null = document.body
if (body) {
body.appendChild(s)
}
// Set state to true so the process doesn't run again
this.setState({
'codepen': true
});
}
}
}
render() {
// Render here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment