Add Support for Syntax Highlighting in a Gatsby Site with @theme-ui/prism

Laurie Barth
InstructorLaurie Barth

Share this video with your friends

Send Tweet
Published a year ago
Updated 10 months ago

[@theme-ui/prism]( is a syntax highlighting component that works with Theme UI. In this lesson, use @theme-ui/prism to select a color scheme for rendering code snippets in MDX files.

Make sure to install @theme-ui/prism@0.4.0-alpha.3.

Instructor: [0:05] Install @theme-ui/prism using the specific .4.-alpha.3 version. In your gatsby-config file, update your gatsby-plugin-theme-ui with prismPreset. We'll use prism-okaidia, but others are available.

[0:26] In your src folder, create a new directory called gatsby-plugin-theme-ui. Inside of it, create a components.js file. Use the @jsx pragma and import Prism from '@theme-ui/prism'.

[0:58] Export a default object. Using the pre key, pass a function that takes props and returns props.children, and for code, pass the Prism component. This will operate on the children props before everything is rendered.

[1:24] Inside your mdx file, use three backticks as code fences and set the language to JavaScript. Let example=egghead be the code snippet.

[1:38] Rerun your project. You'll see the updated code highlighting in syntax. You can also add additional lines of code and use the comment //highlight-line to include built-in code highlighting for a given line.