How to render code snippets in React using Prism

Render code snippets for any language in React using Prism.

Engineering

If you're a software developer, odds are you've had to deal with code snippets at some point. Code snippets are small blocks of code that can be easily reused. In most cases, they're used to save time and avoid repetition.

There are a number of different ways to render code snippets in React, but we're going to focus on one in particular: using Prism. Prism is a lightweight, extensible syntax highlighter that can be used to highlight code in a variety of different programming languages.

Prism's React Component

In this tutorial we will create a Prism React component that can be used to render code snippets in React applications. The component accepts two props: the language of the code snippet and the code itself.

import React, { useEffect } from 'react';
import Prism from 'prismjs';
import 'prismjs/themes/prism-tomorrow.css';

const CodeBlock = ({ language, code }) => {
 const codeRef = React.createRef();
 useEffect(() => {
   if (codeRef.current) {
     Prism.highlightElement(codeRef.current);
   }
 }, [codeRef, language, code]);

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

export default CodeBlock;

Rendering a code snippet is as simple as passing the language and code props to the CodeBlock component. The className prop defines the language of the code snippet, which will be used by Prism to highlight the code accordingly. And that's all there is to it! With just a few lines of code, you can easily render syntax-highlighted code snippets in your React application.

import CodeBlock from "./CodeBlock";

const sampleCode = `function logMsg() {
  console.log("Hello world!");
}
`;

export default function App() {
  return (
    <div className="App">
      <CodeBlock language="js" code={sampleCode} />
    </div>
  );
}

Conclusion

Syntax highlighting is a valuable tool for any software developer. It can make your blog posts easier to read and understand, which is always a good thing. In this tutorial, we've learned how to use Prism to render syntax-highlighted code snippets in React applications. So next time you need to render a code snippet, don't forget about Prism!