Using Prism syntax highlighter in React

OpenJavaScript 0

Last updated: November 6, 2023.

Prism is a popular solution for adding syntax highlighting to code snippets appearing on a web page. Many languages are supported, including HTML, CSS and JavaScript.

This tutorial covers how to set it up in React.

First, you’ll need to install the prism npm library:

npm install prismjs

After this, you can import prism into your project.

Your code needs to be in string format inside <pre> and <code> tags. Using backticks for this minimizes the chance of an unwanted escape:

import Prism from 'prismjs';

function App() {

  return (
    <>
      <pre>
        <code>
          {`
            function add(x, y) {
              return x + y;
            };

            const res = add(5, 7);

            console.log(res); // 12
            `}
        </code>
      </pre>
    </>
  )
}

export default App;
If you want to use backticks within your highlighted code, you should use a backslash before them to prevent it escaping the string containing your code.

You also need to import a CSS file containing the highlight style you want to apply. You can do this by selecting a style from the prism website, then scrolling to the bottom of the page and clicking the “Download CSS” button.

import Prism from 'prismjs';
import './prism.css';

// Code after import

At this point, the code will still not be highlighted. We will need to communicate to prism that we want to render the code as JavaScript and use the library we imported to apply the code highlighting.

To tell prism that the particular code block is JavaScript, add the class of language-javascript to the <code> tag:

<pre>
  <code className='language-javascript'>
    ...Your code here

Now, highlighting can be applied by calling Prism.highlightAll().

But this must occur after the component has rendered so prism has access to HTML it outputs.

Therefore Prism.highlightAll() should be run inside a useEffect() hook, which runs after the component has rendered:

import Prism from 'prismjs';
import './prism.css';
import { useEffect } from 'react';

function App() {

  useEffect(() => {

    Prism.highlightAll();

  },[]);

  return (
    <>
      <pre>
        <code className='language-javascript'>
          {`
            function add(x, y) {
              return x + y;
            };

            const res = add(5, 7);

            console.log(res); // 12
            `}
        </code>
      </pre>
    </>
  )
}

export default App;

Your code should now be successfully highlighted, like below:

Highlighted code using Prism

Normalizing spacing and indentation

In the example above, you may notice some unwanted indentation and spacing that reflects how your code appears in the markup.

You could play around with your markup to remove any indentation any spacing to fix, but this would make your markup hard to read by breaking the normal indentation structure.

Thankfully, you can normalize spacing and indentation by importing and applying the normalize whitespace plugin:

import Prism from 'prismjs';
import './prism.css';
// Plugin must first be imported
import Normalizer from 'prismjs/plugins/normalize-whitespace/prism-normalize-whitespace';
import { useEffect } from 'react';

function App() {

  useEffect(() => {

    // Set prism to normalize spacing and indentation when called:
    Prism.plugins.NormalizeWhitespace.setDefaults({
      'remove-trailing': true,
      'remove-indent': true,
      'left-trim': true,
      'right-trim': true,
    });

    Prism.highlightAll();

  },[]);

  return (
    <>
      <pre>
        <code className='language-javascript'>
          {`
            function add(x, y) {
              return x + y;
            };

            const res = add(5, 7);

            console.log(res); // 12
            `}
        </code>
      </pre>
    </>
  )
}

export default App;

Your code should now look like below:

Highlighted code using Prism and the normalize whitespace plugin