Skip to content
Milind Soorya
Go back

Create react code snippet component

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="max-w-full rounded bg-gray-900 p-2 font-mono text-base text-white 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:-


Share this post on:

Previous Post
8 underrated git commands every programmer should know
Next Post
Connecting Rasa Chatbot to a website - A step by step tutorial