Become a member
to unlock all features

    Syntax Highlighting Code Blocks using Components with Prism React Renderer and Gatsby MDX

    Chris BiscardiChris Biscardi

    Prism is a popular syntax highlighter in the Gatsby ecosystem. Here's how to use the more powerful and flexible component model to enable syntax highlighting in your MDX files using Prism React Renderer.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: 00:00 Here we have an MDX file, a running Gatsby project, and the MDX content in our Chrome window on the right-hand side. Note that we also have an MDX provider providing only a wrapper replacement for our application. To render our MDX code block with Prism syntax highlighting using the React component, we'll install prism-react-renderer.

    00:23 We can use the demo code in the readme directly to implement our initial syntax highlighting component. Note that we haven't copied the example code over. We've also hard-coded the language in our component. To ensure that our component works, we'll copy and paste the example code into the code prop.

    00:48 As you can see, our code is now syntax highlighted using Prism. To get the code block that we wrote in MDX to show up on our page, we'll access the props of the child component of the pre component. Because Markdown code blocks get compiled into a pre component wrapping a code component, we can dive one level deep to get the code.

    01:10 The language attribute in an MDX code block comes through as a class name that looks like language-className. In the case of JavaScript, it'll look like language-js. To get the language from the code component, we drill down at props.children.props.className.

    01:28 If there is no className, that means we might not have put a language on our code block, in which case we'll default to empty string. We then use a named capture group with a name of lang to get the language off the language-className.

    01:44 If there are matches -- if this does not match, matches will be null -- and there are capture groups and there's a capture group called lang, we use the result of that capture group as our language. Otherwise, we use an empty string.

    01:57 Note that this allows us to put no language on the code block or to put a language like JavaScript on the code block. Note that our syntax highlighting has now changed. Now that we have syntax highlighting set up, we can use syntax highlighting for any other language, such as Haskell, or more common languages, such as GoLang.