Code highlighting with PrismJs

2021-01-25

A quick overview on applying styling to code snippets in your website.

The library that I use across this site is called PrismJs it's an easy and clean JavaScript library for styling and highlighting code. It's simple to configure download and use, so I will cover the steps I used to integrate PrismJs into this site below.

The following steps outline the implementation used on this website which is built using NextJs & ReactJs and dynamically pulls the page data from an API.

My requirement is:

  • I need to be able to dynamically highlight code which is retrieved from an API request.

Firstly you need to go the PrismJs website and generate/download a JavaScript and CSS bundle for use in your site. Currently you need to go the download page https://prismjs.com/download.html and select the appropriate themes, languages and plugins.

There are various options you can use to custom the bundles from colour to adding extra functionality like line numbers. Store the downloaded files in a suitable location for future use.

Copy the JavaScript and CSS bundles to the /public folder (e.g. /public/assets/prism.css|.js) of the NextJs application where they can be referenced. Ensure that you place the CSS reference in the NextJs Head tag on the relevant page where you need the code highlighting, e.g.

import React from "react";
import Head from "next/head";

const Meta = () => {
	return (
		<Head>
			<link rel="stylesheet" href="/assets/css/prism.css" type="text/css"/>
		</Head>
	);
};

export default Meta;

Place the JavaScript reference somewhere towards the end of the page - just above the body tag, e.g.

<script src="/assets/js/prism/prism.js"></script>

The next step is apply the markup for the code that needs to be styled in the appropriate component. This code comes directly from the API hence it's rendered as dangerous HTML in reactJs e.g.

<pre><code class="language-bash">echo styling looks good</code></pre>

At the start of the component function add the following code, which will apply the code highlighting/styling

React.useEffect(() => {
	setTimeout(() => (window as any).Prism.highlightAll(), 0);
}, []);

Next you'll have neatly, responsive styled code.