Syntax highlighting for fenced code blocks in Gatsby MDX

My Gatsby setup uses MDX. And i need to add syntax highlighting to the fenced code blocks

Had to install the prism-react-renderer plugin

npm install --save prism-react-renderer

And in my gatsby-browser.js i needed to add the following code

import React from 'react'
import { MDXProvider } from '@mdx-js/react'
import Highlight, { defaultProps, theme } from 'prism-react-renderer'
import github from 'prism-react-renderer/themes/github'

/* eslint-disable */
const component = {
  pre: (props) => {
    const className = props.children.props.className || ''
    const matches = className.match(/language-(?<lang>.*)/)
    return (
        language={matches && matches.groups && matches.groups.lang ? matches.groups.lang : ''}
        {({ className, style, tokens, getLineProps, getTokenProps }) => (
          <pre className={className} style={style}>
            {, i) => (
              <div {...getLineProps({ line, key: i })}>
                {, key) => (
                  <span {...getTokenProps({ token, key })} />
export const wrapRootElement = ({ element }) => {
  return <MDXProvider components={component}>{element}</MDXProvider>

And that's it. Now all fenced code blocks in Markdown will show proper syntax highlighting

The theme i am using came with the plugin, but i plan on creating my custom theme to match the site.

Will probably have to add support for additional languages

Add support for additional languages

You have to install the prismjs package

npm i prismjs

And then add the following to gatsby-browser.js

import Prism from 'prism-react-renderer/prism'

;(typeof global !== 'undefined' ? global : window).Prism = Prism // gotta do this one otherwise it'll say Prism is not defined


You can see a list of included languages here and all supported langs here


Please note that this site and the posts on it are, and will always be, a work in progress. If i waited for perfection, i’d never get anything done.