Created
July 9, 2018 22:12
-
-
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`
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
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