GitHub gist’s are a great way to share code with others. It’s also probably one of the simplest ways you can embed your code into a website.
Best of all you, know GitHub is a reputable company that is not going anywhere, so your code should remain online indefinitely.
Embedding a gist into your website requires you to copy and paste the embed <script> tag into your web-page. The embed script can be found at the top of your gist after creating it.
Once you have copied the code, simply paste it into your HTML where you would like the gist to appear
<div><h1>Your Code Embed</h1><script src="https://gist.github.com/username/gist-id.js"></script></div>
So you have a GitHub gist with multiple files in it. By default, including the gist embed code will display all the files in your gist. If you want to display a specific file, we need to use the file query parameter as follows:
This one left me banging my head on the wall. Simply dropping in the embed code into a react application won’t render anything. Thankfully, a helpful soul on stackoverflow knew why.
It turns out that the GitHub embed script uses “document.write” to insert the code into your page. Not precisely sure how it works, but by the time react inserts the <script> element into the page, it’s too late to write to the document. As such, nothing is displayed.
There are two ways to work around the issue. The first involves loading the script inside an iframe. You can use the NPM package react-gist to achieve this method. It provides a simple component you can call with your gist ID:
const React = require('react');const Gist = require('react-gist');const root = document.getElementById('root');React.render(<Gist id=’5104372’ />, root);
You can even copy and paste the component code from that package as it’s just one file. Might be safer than installing a random package to your code base. I would still suggest staring the repository to show your support.
The next method, which is shown in the stackoverflow post linked above, manually loads the script element and inserts it into the DOM. Someone else created an ES6 version of this that you can find at this GitHub gist which was created by aVolpe. I’ve also added it below just for easy reference.
Let me know if there is another way to do it and I shall add it to this post.