Using highlight.js in React

Updated December 19, 2023 (10 hours ago)

Published March 14, 2022 (2 years ago)

TL;DR: Here's a quick example

If you're making a post or blog, it's important to make sure your code examples are highlighted so that people can read them. Here is a highlighted example snippet:

beforeEach(() => {
  initializeCityDatabase();
});
test("city database has Vienna", () => {
  expect(isCity("Vienna")).toBeTruthy();
});

highlight.js is a very popular package for highlighting code on a webpage. It has great features like:

  • It's themeable

  • It's generic and doesn't require much configuration

  • It can auto-detect the language you're using

Install

Install highlight.js (and optionally marked) into your current project with

npm i highlight.js marked

Implementation

First, make sure that you include the stylesheet with

import "highlight.js/styles/github.css";

In Next.js, this will mean adding the above line to _app.tsx / _app.js.

In React, put the trigger for highlight.js in a useEffect. Copy the following code.

// Very important to import the css file. In next.js, put the following line in `_app.js` instead.
import "highlight.js/styles/github.css";
import hljs from "highlight.js";
import { useEffect } from "react";

function Index() {
  useEffect(() => {
    hljs.highlightAll();
  }, []);
}

You can also use a useLayoutEffect hook for this too. Click here for a full demo.

Sometimes highlight.js has trouble detecting the language of your code. To fix this, you can add a data-language attribute to your code block. For example, in markdown:

```typescript

```

Voila! You're done.

Example

Customizing / Advanced usage

Highlight.js has its options here: https://github.com/highlightjs/highlight.js/#custom-usage

e.g. Highlight custom elements

document.querySelectorAll("pre code").forEach((el) => {
  hljs.highlightElement(el);
});

Theming

highlight.js is themeable, meaning you can make the colours look how you like on a webpage. This is a great for making sure your highlighted code matches the theme of your website.

For dark mode themes dracula-highlight-js is a good pick, and the default theme is good for light mode. There are more themes on the left.

Final words

Please let me know how you go! And thank the product authors for their fabulous products.

Related posts

port-image

Use your favourite games to enhance your users' experience

19 December 2022 (a year ago)