How to use PrismJS with create-react-app

Colourful code highlighting

Need syntax highlighting in your React app? The best library I’ve found for this is Prism; it’s excellent but it requires some unconventional setup for use in a create-react-app powered project.

Steps

1) Create a custom Prism download (be sure to select the languages you want to highlight).

2) Add prism.css to /public/css/prism.css

3) Add prism.js to /public/js/prism.js

4) Import the files from the previous steps in /public/index.html:

<!-- PrismJS v1.22.0
  With JSX extension.
  'data-manual' disables automatic highlighting (which is desirable as this
  should be controlled by React). https://prismjs.com/#basic-usage
-->
<script src="%PUBLIC_URL%/js/prism.js" data-manual></script>
<link rel="stylesheet" href="%PUBLIC_URL%/css/prism.css" />

5) Use Prism:

// Highlight all <code> elements with 'language-XXXX' class
// where XXXX is a Prism alias.
useEffect(() => {
  window.Prism?.highlightAll();
});

Extra: highlighting specific <code> blocks

If you don’t want to highlight all <code> blocks, save a ref to the block you want to highlight and use Prism.highlightElement().

Here’s an example:

// https://codesandbox.io/s/prismjs-and-react-u31oj?file=/src/components/HighlightedCode.js
import React, { useEffect, useRef } from "react";
import PropTypes from "prop-types";

HighlightedCode.propTypes = {
  code: PropTypes.string,
  langauge: PropTypes.string
};
HighlightedCode.defaultProps = {
  code:
    "import React from 'react';\n\nconst Welcome = () => <p>Hello Prism!</p>;",
  language: "jsx"
};
export default function HighlightedCode(props) {
  const { code, language } = props;
  const codeEl = useRef(null);

  // Highlight with Prism.
  useEffect(() => {
    if (!codeEl.current) return;
    window.Prism?.highlightElement(codeEl.current);
  });

  return (
    <pre>
      <code ref={codeEl} className={`language-${language}`}>
        {code}
      </code>
    </pre>
  );
}