How to create code blocks in MDX & Gatsby

I am going to show you how to create and add code blocks in MDX, building a code block component to use in your MDX for React or Gatsby projects.

#Gatsby#React#PrismJs
Dom Vournias
Dom Vournias
Updated on: 04 Jan, 2022

Create a code block component

Install Prism for MDX

We are going to use Prism so we can then go ahead and create the component. First install Prism

npm i prismjs
yarn add gatsby-plugin-mdx-prismjs
yarn add @mdx-js/mdx @mdx-js/loader loader-utils --dev

Include in gatsby-config.js

// gatsby-config.js
---
plugins: ['gatsby-plugin-mdx-prismjs'],

You can read more about Prism here.

Create the code block component

Create a new component and called it however you like. In this example I will call it Code.js

// Code.js
---
import React, { useEffect } from "react";
import Prism from "prismjs";
import "../../styles/prism.css";
---
export default function Code({ code, language }) {
  useEffect(() => {
    Prism.highlightAll();
  }, []);
  return (
    <div className="my-10">
      <div className="Code">
        <pre className={/* Inside template literals -> */language- $ {language} }>
          <code>{code}</code>
        </pre>
      </div>
    </div>
  );
}

Style the code block component

Create a css file called prism.css and make sure to import it in your code block component.

Choose a Prismjs theme

//prism.css
--- 
Prism Theme CSS

Insert code block component in MDX

To finalize we have to import the code component in our MDX file and start writing our code.

//YourPost.mdx
---
import Code from "./Code";
/*Content...*/
<Code code={/*code goes between template literals ''*/} languate="javascript"/>

Customizing the fonts of Prism block

If you've followed all the steps correctly then you'll have a prism code block exactly like mine except from the typography.

Customizing the fonts of Prism block
Customizing the fonts of Prism block

To add the typography you will have to include the font-styles in the correct css class inside prism.css file.

//prism.css
---
/*Tokens*/
.token.string,
.token.comment {
  font-family: Menlo, Monaco, Consolas, "Andale Mono", "Ubuntu Mono",
    "Courier New", monospace;
}

Conclussion

You can customize your prism code blocks to suit your style with the tools I mentioned above and further expand the functionality of the component.


I hope this guide helped you create beautiful code blocks to highlight your coding. Make sure to leave a 👍 and love ❤️ if you found this article helpful.

ARTICLE REACTIONS

SHARE THIS POST

Dom Vournias Portfolio
Get in touch

If you want to work together on a project or to just have a chat, please don't hesitate to contact me.

about
Dom Vournias signature