Joseph Mawa A very passionate open source contributor and technical writer

The guide to syntax highlighting in React

6 min read 1854

The guide to syntax highlighting in React

Software developers read as much code as they write. Therefore, to enhance code readability, you should not only strive to write readable code but also apply appropriate code formatting and syntax highlighting.

There are several programming and non-programming computer languages developers use daily. Each language comes with its syntax and, therefore, syntax highlighting needs. To apply syntax highlighting in the browser environment, libraries such as Prism, Highlight, and React syntax highlighter exist.

Each of these libraries has its strengths and weaknesses. Some of these libraries have been developed for use with plain JavaScript, while others also support front-end frameworks like React.

This article will be a complete guide to popular syntax-highlighting libraries like Prism and how to use them with React. We will also highlight their strengths and weaknesses.

Table of Contents

Introduction to prism.js

Prism is one of the most popular syntax highlighting libraries in JavaScript, with over 10,000 stars on GitHub. You can use it with plain JavaScript and frameworks such as React. It supports several languages and has a rich ecosystem of themes and plugins that you can use to extend its core functionality.

To get a taste of Prism, you can quickly load it via CDN or download the source code and add it to your markup using a script tag. You can also download support for specific languages, themes, and plugins.

The core Prism library has a small footprint. Its minified and gzipped bundle size is approximately 2kB. Though the additional themes and plugins you download with core Prism to extend its functionality may increase the bundle size, you have total control over which plugins or themes you can download.

Additionally, unlike some syntax highlighters, Prism forces you to use semantic HTML for code presentation. The customizability, and several other features, make Prism a popular choice for syntax highlighting.

Babel-plugin-prismjs is a handy package for using Prism with Babel and webpack. In the next section, we shall look at using this plugin in a React application.

How to use Prism for syntax highlighting in React

As mentioned in the previous section, the easiest and fastest way to get started with Prism is to use a CDN. Though a CDN may be convenient, it is almost always impossible to use it when working with frameworks such as React. Therefore, you will need to install it from NPM.

# using npm
npm install prismjs
# using yarn
yarn add prismjs

The babel-plugin-prismjs Babel plugin comes in handy if you want to use Prism for syntax highlighting in a React application. You can use it to configure the languages, themes, and plugins to bundle with Prism. You can install it as a development dependency from NPM.

# using npm
npm i -D babel-plugin-prismjs
# using yarn
yarn add -D babel-plugin-prismjs

You need to register the plugin in your Babel configuration file like so:

{
  "plugins": [
    ["prismjs", {
        "languages": ["javascript", "css", "markup"],
        "plugins": ["line-numbers"],
        "theme": "twilight",
        "css": true
    }]
  ]
}

You can include the languages, plugins, and themes your project needs in the configuration file. Check the Prism documentation for a complete list of the supported languages and the available themes and plugins you can use.



Set up a custom react application if you want to use the babel-plugin-prismjs plugin. However, to use it with Create React App, you will need to eject — I believe doing so defeats the purpose of using Create React App.

Additionally, several React syntax highlighting packages use Prism under the hood. We shall explore some of them in the sections below. You might consider using one of them if your project is not based on a custom React application.

After completing the setup described above, import Prism into your React component and invoke the highlightAll method in the useEffect hook like so:

import React, { useEffect } from "react";
import Prism from "prismjs";

function App() {
  useEffect(() => {
    Prism.highlightAll();
  });
  return (
    <div>
      <p>
        You can declare a variable in JavaScript using the
        const, let or var keyword. </p> </div> ); } export default App;

When using Prism, you need to wrap inline code in the code HTML tag, and depending on the language you are highlighting, apply the appropriate class to it. The class name should take the form lang-xxxx or language-xxxx.

The xxxx is a placeholder for the language. In the example above, we added the lang-javascript class to the code elements since we are highlighting JavaScript code.

As pointed out in the previous section, Prism forces you to use semantic HTML when adding code to your markup. Therefore, you must wrap your code in pre elements when highlighting blocks of code.

It is convenient to extract your functionality to a separate component for reusability when rendering code blocks, like in the example below. You can pass the code block and the language as props.

import React, { useEffect } from "react";
import Prism from "prismjs";

const CodeBlock = ({ code, language }) => {
  useEffect(() => {
    Prism.highlightAll();
  }, []);
  return (
    <pre>
      <code children={code} className={`language-${language}`} />
    </pre>
  );
};

export default CodeBlock;

How to use prism-react-renderer

Instead of using Prism with a React application as we did in the previous section, you can also use prism-react-renderer to highlight code in your React application.

prism-react-renderer comes bundled with a modified version of Prism, and it provides support for some of the common languages and themes by default.


More great articles from LogRocket:


You need to install prismreactrenderer from NPM to use it.

sh
# install with npm
npm i prism-react-renderer

# install with yarn
yarn add prism-react-renderer

Prism react renderer exposes Highlight as its main component and exports some default props, which you can pass to Highlight. You need to pass a render prop to the Highlight component as in the example below.

import React from "react";
import Highlight, { defaultProps } from "prism-react-renderer";

export const CodeBlock = ({ code, language }) =&gt; {
  return (
    &lt;Highlight {...defaultProps} code={code} language={language}&gt;
      {({ className, style, tokens, getLineProps, getTokenProps }) =&gt; {
        return (
          &lt;pre className={className} style={style}&gt;
            <code>
                  {tokens.map((line, idx) => {
                    return (
                      <div {...getLineProps({ line, key: `line-${idx}` })}>
                        {line.map((token, i) => {
                          return (
                            <span
                              {...getTokenProps({ token, key: `token-${i}` })}
                            />
                          );
                        })}
                      </div>
                    );
                  })}
                </code>
          &lt;/pre&gt;
        );
      }}
    &lt;/Highlight&gt;
  );
};
</code></pre>

The above code block illustrates how you can highlight a simple code block with the prism-react-renderer package. The Highlight component passes several arguments to the render prop. You can use these props to render your code block like in the above example.

You can import the CodeBlock component we wrote above and pass in the code and language props when rendering a code block. Doing so makes the component reusable.

import { CodeBlock } from "./CodeBlock";

const code = `
  const add = (a, b) => {
    return a + b;
  }
`;

function MyComponent() {
  return (
    <div className="App">
      <CodeBlock code={code} language="javascript" />
    </div>
  );
}

Introduction to react-syntax-highlighter

react-syntax-highlighter is a React component for syntax highlighting in React. It uses Prism and Highlight for syntax highlighting internally. Prism and Highlight are among the popular syntax highlighters for the browser environment.

You install it from NPM and pass in the necessary props to start using react-syntax-highlighter.

# using npm
npm i react-syntax-highlighter

# using yarn
yarn add react-syntax-highlighter

Unlike some of the packages described in the previous sections, you don’t need extra configuration to get this to work. Let us look at how to use it for syntax highlighting in React in the section below.

How to use react-syntax-highlighter

After installing react-syntax-highlighter, you can import and render the necessary component. As mentioned in the previous section, you can choose to either use Highlight or Prism for highlighting.

However, react-syntax-highlighter exports a component that uses highlight by default. You need to pass the configuration option as props when rendering it like so:

import SyntaxHighlighter from "react-syntax-highlighter";
import { dracula } from "react-syntax-highlighter/dist/esm/styles/hljs";

const code = `
console.log("hello world");
`;

function App() {
  return (
      <SyntaxHighlighter children={code} language="javascript" style={dracula} />
  );
}

As illustrated in the example above, you pass the code you want to highlight and the formatting language as string props. In addition to the children, language, and style props, there are several other formatting options, such as displaying and styling line numbers. Do check the documentation for a complete list of options available.

As pointed out in the introduction, react-syntax-highlighter comes bundled with both Highlight and Prism. Instead of using Highlight as in the above example, you can also use Prism. When using Prism, you also need to import the Prism theme you want to use, like in the example below.

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { dark } from 'react-syntax-highlighter/dist/esm/styles/prism';

Though the method for using it described above loads several features out of the box, it comes with a large footprint. Therefore, react-syntax-highlighter has a light build for loading and bundling only the functionalities you need.

However, be aware that the light build doesn’t come with default styling. Therefore, you need to import the theme by yourself. Additionally, import and register the languages using the registerLanguage function as in the example below.

import { Light as SyntaxHighlighter } from "react-syntax-highlighter";

import typescript from "react-syntax-highlighter/dist/esm/languages/hljs/typescript";
import a11yDark from "react-syntax-highlighter/dist/esm/styles/hljs/a11y-dark";

SyntaxHighlighter.registerLanguage('typescript', typescript);

The above example for the light build uses Highlight by default. You can use Prism similarly. Import PrismLight instead of Light, as in the example below.

import { PrismLight as SyntaxHighlighter } from "react-syntax-highlighter";

import typescript from "react-syntax-highlighter/dist/esm/languages/prism/typescript";
import a11yDark from "react-syntax-highlighter/dist/esm/styles/prism/a11y-dark";

SyntaxHighlighter.registerLanguage('typescript', typescript);

Check the documentation for more features and limitations of the react-syntax-highlighter package.

Introduction to Rainbow

The syntax highlighting libraries mentioned above are the most popular and easiest to use with React.

However, they are not the only syntax highlighting libraries. Rainbow is another simple and lightweight package for syntax highlighting. It is worth exploring, especially when you are not using a framework like React.

Conclusion

Syntax highlighting is inevitable when publishing content containing inline code snippets or code blocks to increase readability. There are several libraries you can pick from when highlighting code in the browser environment — the most popular syntax highlighting libraries are Prism and Highlight.

As mentioned above, you can use some syntax highlighting libraries with plain JavaScript and others with frameworks like React. The babel-plugin-prismjs Babel plugin lets you use Prism with bundlers such as webpack. However, you can also use React packages such as prism-react-renderer or react-syntax-highlighter which bundle modified versions of Prism.

Prism has a small footprint when considering the core library. However, it becomes sizable when you extend its core functionalities with additional themes and plugins.

Though our focus in this article was on syntax highlighters usable with React, several other Syntax highlighting libraries like Rainbow are also worth exploring. Rainbow is a great syntax highlighting library to consider if you are not using a front-end framework like React.

LogRocket: Full visibility into your production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket combines session replay, product analytics, and error tracking – empowering software teams to create the ideal web and mobile product experience. What does that mean for you?

Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay problems as if they happened in your own browser to quickly understand what went wrong.

No more noisy alerting. Smart error tracking lets you triage and categorize issues, then learns from this. Get notified of impactful user issues, not false positives. Less alerts, way more useful signal.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Joseph Mawa A very passionate open source contributor and technical writer

Leave a Reply