Create react code snippet component
Milind Soorya / May 22, 2021
2 min read
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
- First download the highlight.js package from npm, by
npm install highlight.js --save
- 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>
);
}
- 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.😃