How to highlight code and auto detect the language with react-markdown
For my blog I use the package react-markdown to render markdown content, there are different options to highlight the code blocks with it, in general the most famous and reliable syntax highter libraries are two: Prism and Highlight.js.
In my case I don't specify the language of the blocks so I needed a solution that also auto detect the language. Since that feaure is present only in highlight.js, I've chosen it.
To use it with react-markdown the easiest way is to use rehype-highlight that hooks it up to the transformation tools that react-markdown uses under the hood.
So install both libraries with:
yarn add rehype-highlight highlight.js
And then use them like follow:
import "highlight.js/styles/github-dark.min.css";
import ReactMarkdown from "react-markdown";
import rehypeHighlight from "rehype-highlight";
import remarkGfm from "remark-gfm";
const rehypeHighlightWithAutoDetect = (options) =>
rehypeHighlight({ ...options, detect: true });
export default function MardkownViewer({ content, className }) {
return (
<ReactMarkdown
className="markdown prose"
children={content}
remarkPlugins={[remarkGfm, remarkToc]}
rehypePlugins={[rehypeHighlightWithAutoDetect]}
/>
);
}
The main function that I couldn't find on the web is rehypeHighlightWithAutoDetect
that passes the detect: true
argument to rehype-highlight since it's false
by default.