Create react code snippet component

Milind Soorya / May 22, 2021

2 min read

highlight-code-blocks-in-react

What is it?

In a recent project while creating a website, I had to create a code block area to show the code segments, after some research I landed on highlight.js but its implementation part is really hard for a beginner to understand, hence after some experimentation I created this functional component in React so that I can pass the code blocks as children and it will handle the rest.

It will look almost like the code sections below, I used some tailwind css to style the code block, but styling is all up to you.

Usage

  1. First download the highlight.js package from npm, by
npm install highlight.js --save
  1. Now create a component and paste the following code
// components/CodeHighlighter.js
import hljs from 'highlight.js';
import react, { useEffect, useRef } from 'react';
import 'highlight.js/styles/foundation.scss';
export default function CodeHighlighter({ children }) {
  const preRef = useRef(null);
  useEffect(() => {
    hljs.highlightElement(preRef.current);
  }, []);
  return (
    <pre
      ref={preRef}
      className="bg-gray-900 rounded max-w-full
text-white font-mono text-base p-2 md:p-4"
    >
      <code className="break-words whitespace-pre-wrap">{children}</code>
    </pre>
  );
}
  1. You can use this by importing this component and passing the required code as a string like this
<CodeHighlighter>{`console.log("Hello world")`}</CodeHighlighter>

Customization

As I mentioned above you can customize it any way you want, and the code styling can be accomplished buy importing any of the scss from your node_module/highlight.js/scss folder. Also checkout this highlight.js documentation for viewing all the available styles. That's it, do leave a comment if you need any help.😃

You might also like:-

Learn about building products as a Data Scientist

Get a once-per-month email with my latest article and additional details about my launches, products, and experiments ✨

No spam, sales, or ads. Unsubscribe as your heart desires.