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!
What is Gist? Gist is an easy method to share snippets or excerpts of data with others. A gist can be a string of code, a bash script or some other small piece of data. These bits of information are hosted by GitHub as a repository.
use this npm package, worked for me.
Step 1: Install the package
npm i react-gist
Step 2: import in your react component
import Gist from "react-gist";
Step 3: put your gist id
<div>
<Gist id="f824ffb7bafec535d0b6452179f2d790" />
</div>
OR
<div>
<Gist id='f824ffb7bafec535d0b6452179f2d790' file='java-file' />
</div>
if you have multiple files in the same gist
<Gist id={string} file={string} />
Where,
id {string} Id of the gist file
{string} Name of a specific file in a multi-file gist
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!
This solution lets you embed anything in an iFrame:
import Frame from 'react-frame-component';
<Frame initialContent="<!DOCTYPE html><html><head></head><body><script src='https://gist.github.com/[YourUsername]/aa7101515bb1586857ca43beac8e0abc.js'></script></body></html>" />
Just replace the gist url in the code above with your own.
Frame component available at: https://www.npmjs.com/package/react-frame-component
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With