How to Embed Codepen in Gatsby Markdown

Learn how to embed Pen’s (from CodePen) in GatsbyJS markdown files.

In GatsbyJS, markdown is the default language that most Gatsby site owners use to write their content (blog posts, tutorials). If you’re writing a lot of coding tutorials, like me, you’ll do your audience a service by sometimes embedding a coding playground as a reference, as your readers are following along.

Fortunately, there’s a Gatsby Plugin that easily allows you to embed CodePen’s in your markdown files, called gatsby-remark-codepen.

To install gatsby-remark-codepen, open your terminal, go to your Gatsby websites root folder, and run the following command:

If you’re using NPM

npm install --save @weknow/gatsby-remark-codepen

If you’re using Yarn

yarn add @weknow/gatsby-remark-codepen

Here’s the official repository for gatsby-remark-codepen.

Add your plugin to gatsby-config.js

After installing the plugin, go to your gatsby-config.js file, and add your newly installed CodePen plugin, by inserting it as an object in your plugins array.

I know the gatsby-config.js file can look a bit confusing to newcomers (all those curly braces and brackets). Here’s the specific code that you need to add to your array to enable the gatsby-remark-codepen plugin:

{
        resolve:"@weknow/gatsby-remark-codepen",
        options: {
          theme: "dark",
          height: 400
        }
      }

And here’s how it looks when added currectly inside my gatsby-config.js file:

plugins: [
  {
    resolve: "gatsby-transformer-remark",
    options: {
      plugins: [
        {
          resolve:"@weknow/gatsby-remark-codepen",
          options: {
            theme: "dark",
            height: 400
          }
        }
      ]
    }
  }
];

Make sure that you add it the correct place. If there are other objects in your array, remember to separate them wih with a comma (,).

Add Pens in your markdown files

Now you’re ready to add Pen’s inside your markdown files, and it could not be more simple. Just copy & paste the link from your CodePen and it will automatically show up. So if your Pen has the following URL: https://codepen.io/StrengthandFreedom/pen/LeyjXG just add it like this:

#### Use this Pen as a reference

https://codepen.io/StrengthandFreedom/pen/LeyjXG

And it will automatically show up like this:

https://codepen.io/StrengthandFreedom/pen/LeyjXG

Troubleshooting

If your Pens show up a regular link, then first check if you have any errors in your terminal or console. If you have, you probably screwed up the gatsby-config.js file. If you don’t have any errors, try restarting your Gatsby server.

If that still doesn’t work, shut down your server and delete your .cache from your Gatsby site’s root directory — and start your server again. That should do it!

Happy coding :)


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on