Search code examples
reactjsgist

How can I embed a Github Gist inside of a React component?


I'm trying to use the Github Gist API to get all of my gists and embed them on a web page. Each Gist holds a blog post that I contain within the following component:

function BlogEntry(gist)  {
    return (
        <div>
            {gist.createdAt} {gist.id} {gist.description}
            <script src={"https://gist.github.com/seisvelas/" + gist.id + ".js"}></script>
        </div>
    );
}

The first line of the render'd div, {gist.createdAt} {gist.id} {gist.description} works, so I know I'm successfully interacting with the API. However, the second part with the script tag does nothing.

I tried this on a plain HTML document and he pattern <script src="https://gist.github.com/seisvelas/gist_id.js"></script> (which I got from the Gist website itself) does work given a valid gist_id.

I'd guess this has to do with how script tags behave in React components. It hadn't even occurred to me that this would be an issue. Could anyone recommend a simple workaround so I can get these Gists embedded successfully?

Thanks!


Solution

  • For anyone else who runs into this problem, I resolved it using the npm package react-embed-gist. It's dead simple and looks like this:

    import ReactEmbedGist from 'react-embed-gist';
    
    // Only required attribute is gist
    <ReactEmbedGist gist="msaracevic/5d757e2fc72482a9a4a439969500c2eb"
                    wrapperClass="gist__bash"
                    loadingClass="loading__screen"
                    titleClass="gist__title"
                    file=".bash_profile.sh"/>
    

    Highly recommend!