How to Add Syntax Highlighting in Gatsby Blog Posts
Syntax highlighting is a feature that displays source code in different colors and fonts according to the category of terms. It's a great way to improve the readability and context of the code in your blog posts. In Gatsby, one of the popular libraries for syntax highlighting is highlight.js
. In this guide, I'll show you how to add syntax highlighting to your Gatsby blog using highlight.js
.
Step 1: Install highlight.js
The first step is to install the highlight.js
library. You can do this using npm or yarn:
npm install highlight.js
or
yarn add highlight.js
Step 2: Import highlight.js
and its styles into your template
Once you've installed highlight.js
, you need to import it and its styles into your blog post template.
You can choose from various styles that highlight.js
provides. For this example, we'll use the github-dark.css
style, but feel free to explore other styles available in the highlight.js
repository.
Also, to ensure that the code doesn't overflow from its container, especially when you limit the width, it's a good practice to set the white-space
property to pre-wrap
.
Here's how you can set it up:
import hljs from "highlight.js"
import "highlight.js/styles/github-dark.css"
export default function BlogTemplate({ data }: { data: BlogPostData }) {
const { markdownRemark } = data
const { frontmatter, html } = markdownRemark
// Using the useEffect hook to highlight the code when the component mounts
useEffect(() => {
hljs.highlightAll()
}, [])
return (
<Layout lightFooter={frontmatter.review === null}>
<Section>
<div className="prose mx-auto prose-code:whitespace-pre-wrap">
<h1>{frontmatter.title}</h1>
<div dangerouslySetInnerHTML={{ __html: html }} />
</div>
</Section>
</Layout>
)
}
Conclusion
Adding syntax highlighting to your Gatsby blog is a straightforward process with highlight.js
. With just a few lines of code, you can significantly improve the readability of your code snippets and offer your readers a better user experience. Happy blogging!
Lassen Sie uns zusammenarbeiten
Gerne können wir in einem Telefonat besprechen, wie wir zusammenarbeiten könnten, um Ihr Projekt zu realisieren.
Kontaktieren Sie mich, um loszulegen