Frontend developer focused on inclusive design

Syntax highlighter in React

Since I document my journey of learning new skills, with a great focus on a web development, I often need to include code snippets in my posts.

By default, a visual presentation of a code section is not very appealing. To improve the user experience of these sections, I decided to use a code highlighter.

Below you can find instructions of enabling syntax highlighting in React.

Install react-syntax-highlighter

To allow for code highlighting, use a special syntax highlighting component for React from react-syntax-highlighter package.

To install the package, run the following command in the terminal in the root of your project:

npm install react-syntax-highlighter --save

This command will add react-syntax-highlighter to your package.json.

Create Code component

This React component is designed to hold the styles and other properties related to a code section, including react-syntax-highlighter.

Create Code.js file in your components folder, and add the following code to it:

// components/Code.js
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { dracula } from 'react-syntax-highlighter/dist/cjs/styles/prism';

const Code = ({ language, children }) => (
    <SyntaxHighlighter language={ language } style={ dracula }>
        { children }
    </SyntaxHighlighter>
);

export default Code;

The component uses Prism, included in react-syntax-highlighter, to style code syntax.

The code output (children), added to this component, will be automatically styled based on a set style. In this specific case, the component uses dracula style, from a list of availible Prism styles, to provide a code highlighting.

Not to mention, the component allows to set language to highlight code in. Here is a list of available languages for Prism in react-syntax-highlighter.

Use Code component

In order to highlight a code on a page, make sure to tell the page to use the Code component.

To do so, import the Code component to a page by adding this code at the top of the page file:

import Code from '../components/Code';

Then, wrap your code output within the Code component:

<Code language="javascript">
 Your code output goes here.
</Code>

In this specific case, the Code component uses javascript as the language to highlight code in.