Gatsby: Code syntax highlighting with react-prism-renderer
I write coding tutorials for different programming languages.
Since I use Gatsby, for syntax highlighting I added react-prism-renderer, which is a wonderful plugin to do it. By default, it comes with a variety of coding languages enabled. This is the component that I use to display my code examples in this page.
But when I was writing some snippets, I saw that some languages weren’t highlighted by default. There was a lack of syntax color. What was the problem?
Update 2023: I don’t use this plugin anymore. I’m using Shiki Highlight
🧱 My syntax highlight component
Under the hood, React prism renderer uses PrismJS, and we can use it as our advantage. We need to import language by language that we need to add support for it.
Here is the code. With this snippet, we can create a Gatsby React’s component. Pay attention to the require lines.
Then, if you’re using MDX or something similar to create your pages. You can use the component as you can see here
Now all your HTML <code> tags will have syntax highlight.
🎙 Explaining the code
The <Highlight/> component is used by react prism renderer to create the code syntax color that you can see.
If we see the import part of the coding languages, we will see that we need to load some of them. This is made to just only load what you need. I’d recommend you to visit the /node_modules/prismjs/components/ folder.
Source from fixing language highlighting: here . This tutorial is an extension from the original answer.
The code from the component could be outdated. Always take a look to my main Code component here
My posts are not AI generated, they might be only AI corrected. The first draft is always my creation