Creating a Gist component for

A short hello

Hello and welcome to my first post on my new blog. I've recently migrated my old post from Medium to Gatsby + and I could not be happier with the outcome.

As a first experiment I wanted to rebuild the Gist embed function existing on medium.

Like so:

...waiting for Gist...

Project setup

This blog is created by using the original Sanity + Gatsby blog template. You can read a handy guide here on the official site.

I've added an additional npm package - gatsby-plugin-web-font-loader to load a font to my liking, but that is it as far as customizations go before implementing the Gist embed.

Gist entry in Sanity

To begin using Gists as an object in Sanity, we need to define it and add it to our schema.

Let's create a new schema definition called gist.js:

...waiting for Gist...

To let sanity know that we have an object type, we need to add it to our schema.js file.

Example from my project:

...waiting for Gist...

If we now open up Sanity and check a rich text editor we would not see anything there. To add it there, we need to modify the schema for the rich text field. In case of the template I'm using, the name of the object was bodyPortableText. This might differ for your case.

Example from my project:

...waiting for Gist...

Notice in the above snippet we have added the object with type 'gist' to the end of the list. This will add a new selection option in our body rich text field.

Gist embed

However, to let sanity know how to preview the gist in our editing interface, we will need to let it know which component to use. I've decided to use the super-react-gist package for that purpose.

Let's install the super-react-gist package and modify the gist.js file like so:

...waiting for Gist...

Notice we have added 'preview' section to the schema config. This tells Sanity to render our Preview component in the editor:

Gist preview

Now this is the editing portion done, however Gatsby now won't know how to render the Gist. Let's do that next.

Adding Gist component to Gatsby

To let Gatsby know how to render the Gist, we will need to modify the serializers that we pass to the @sanity/block-content-to-react BasePortableText component.

Let's go the our serializers.js file and add a new serializer. This configuration might be on in a different location for you:

...waiting for Gist...

That should be it!

As it turns out, adding custom previews and components to Sanity and Gatsby is fairly simple. There is also room for a lot of code and npm package reuse between the administration interface and the frontend, since both are just React applications.