Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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) {
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 = `//` = 'codepen-script'
const body: HTMLElement | null = document.body
if (body) {
// Set state to true so the process doesn't run again
'codepen': true
render() {
// Render here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.