paint-brush
Using PrismJS as a Syntax Highlighter in Reactby@itsmycode
20,649 reads
20,649 reads

Using PrismJS as a Syntax Highlighter in React

by Srinivas RamakrishnaNovember 10th, 2021
Read on Terminal Reader
Read this story w/o Javascript

Too Long; Didn't Read

PrismJS is a library written using JavaScript, which is used for syntax highlighting or code highlighting. It's one of the most popular libraries used by millions of websites to highlight the code block. Prism is lightweight (2KB), intuitive, blazing-fast and extensible compared to other libraries. The language is defined through the way recommended in the HTML5 draft: through a language-xxxx class. There are plugins for Prism which provides additional features, and if there is a need, you could select the relevant plugins using the checkbox.

Company Mentioned

Mention Thumbnail
featured image - Using PrismJS as a Syntax Highlighter in React
Srinivas Ramakrishna HackerNoon profile picture


PrismJS is a library written using JavaScript, which is used for syntax highlighting or code highlighting. It's one of the most popular libraries used by millions of websites to highlight code blocks.


Why PrismJS?

There are various other libraries such as highlight.js, Syntaxhighlighter, Rainbow etc. However, Prism stands out as unique among the crowd because of the various features it offers. Prism is very lightweight (2KB), intuitive, blazing-fast, and extensible compared to other libraries.


Features of PrismJS

Let's take a look at the core features of Prism. For the entire set of features, refer to the official PrismJS website.


  • Very Lightweight, the core library is of 2KB Size when minified and gzipped.
  • Supports a wide variety of languages. According to the official documentation, it supports 275+ languages.
  • Easy to implement on any tech stack like WordPress, React, Angular etc
  • PrismJS can be easily extended with the help of a hook and without modifying the code.
  • Easy to extend or define new languages with the understanding of regular expression.
  • Supports most browsers; Edge, IE11, Firefox, Chrome, Safari, Opera.
  • Enforces the use of the <code> mark up and also supports inline code with <pre> tags. The language is defined using the HTML5 draft recommendation: through a language-xxxx class.


How to add Prism.js Syntax Highlighting to any Website?

Implementation of PrismJS is straightforward and does not require much in-depth coding knowledge.


Step 1: Download the PrismJs library from the official website by clicking on the download button.


Select the minified version, the theme you like, and checkmark all the coding languages that you want Prism to recognize and highlight in your website or article.


There are plugins for Prism which provide additional features. if you need those, you could select the relevant plugins using the checkbox.


Step 2: Once you have finished the selection, click on the Download JS and Download CSS button at the bottom of the page to download the generated prism.js and prism.css files.


Step 3: Include the prism.css and prism.js files that you have downloaded on the HTML page, as shown below.


<!DOCTYPE html>
<html>
<head>
	...
    <link href="css/prism.css" rel="stylesheet" />
</head>
<body>
	...
    <script src="js/prism.js"></script>
</body>
</html>


Step 4: The files are included, and you are ready to use them as a syntax highlighter. Let’s highlight some CSS code as an example.


If you want to highlight CSS code, you need to use the class “language-css”. For JavaScript, it will be “lang-js” or “lang-JavaScript“.


For CSS

    <pre><code class="language-css">p { color: red }</code></pre>


For JavaScript

    <pre><code class="language-js">console.log("Hello World")</code></pre>


Note: Do not add any space between the <pre> and <code> the same will be displayed on the page. Also since it’s a plain HTML do not add any line breaks inside the <pre> and <code> tags.


For the entire list of classes for each language, you can refer to https://prismjs.com/#languages-list


How to get PrismJS Working in React

Step 1: Install the PrismJS and babel-plugin-prismjs package using the npm command as shown below. The babel plugin is responsible for loading the CSS and language support for Prism.js.


Note: To make it easy to configure your Prism instance with only the languages and plugins you need, use the babel plugin babel-plugin-prismjs. This will allow you to load the minimum number of languages and plugins to satisfy your needs.


$ npm install prismjs $ npm install babel-plugin-prismjs


Step 2: In your .babelrc, register the plugin and configure its dependencies. Here you can set the languages, themes, plugins etc. If you do not already have a .babelrc file, create one in the root folder of your source code and add the following JSON to the .babelrc file.


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


Step 3: Create a simple react component code.js and import PrismJS into your react component and configure the component to read the language props from App.js Below is the snippet of the code.js component.


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

export default function Code({ code, language }) {
  useEffect(() => {
    Prism.highlightAll();
  }, []);
  return (
    <div className="Code">
      <h2> Code Syntax Block {language}</h2>
      <pre>
        <code className={`language-${language}`}>{code}</code>
      </pre>
    </div>
  );
}


Step 4: In the App.js import and call the code component as shown below. Pass the props (language and code syntax) dynamically to the code component.


<Code code={JSCode} language="javascript" /> <Code code={htmlCode} language="html" />


app.js code for your reference.

import React from "react";
import Code from "./components/Code";

const JSCode = `const App = props => {
  return (
    <div>
      <h1> Prism JS </h1>
      <div>Awesome Syntax Highlighter</div>
    </div>
  );
};
`;

const htmlCode = `
    <div>
      <h1> PrismJS Tutorial </h1>
      <p>
      Prism is a lightweight, extensible syntax highlighter, built with modern web standards in mind.
      </p>
    </div>
`;

export default function App() {
  return (
    <div className="App">
      <Code code={JSCode} language="javascript" />
      <Code code={htmlCode} language="html" />
    </div>
  );
}


Step 5: Run the react application using npm run start and you should see PrismJS highlighting the code automatically.


The sample PrismJS React tutorial is hosted in the Github repo, feel free to download and modify according to your needs.


First published here