All posts

How to use PrismJS in ReactJS.

An overview of my 2023 guide to highlighting code in React with PrismJS, using C++ as the example language.

ReactPrism.jsJavaScript

Load Prism and its theme

Install PrismJS in an existing React project, then import Prism and a theme stylesheet. The original example uses the Okaidia theme.

JavaScript · Prism and theme imports
import Prism from 'prismjs';
import 'prismjs/themes/prism-okaidia.min.css';

Add language support

Load the C language component before the C++ component, since C++ highlighting depends on it. The guide also uses Prism’s normalize-whitespace plugin to tidy the code.

Highlight after rendering

Place the source inside pre and code elements, using className="language-cpp" on the code element. Call Prism.highlightAll() from React’s useEffect after the component renders so Prism can highlight the DOM.