Use Markdown To Power Your Site Content With Next.js

Publish Date - 5th April 2022

Last Updated - 5th April 2022

For this website, I write all blog posts in markdown files.

There are a few things required to make that happen. In this post I will focus on setting up and using the react-markdown library.

Install React Markdown

Install react markdown with npm i react-markdown.

Install react-syntax-highlighter with npm i react-syntax-highlighter

The react-syntax-highlighter is used to add syntax highlighting to <code></code> blocks.

If you are using Typescript, you also need to npm i --save-dev @types/react-syntax-highlighter

Extract Markdown from A Markdown File

There are many ways to extract markdown from a file saved on the file system. That is outside the scope of this aricle. In the below example, I am assuming the markdown has been extracted.


import ReactMarkdown from "react-markdown";

export default function Page() {

const content = `
    
    #Headline 

    Paragraph content

    ```javascript

    const x = "Markdown"

    ```

}

Wrap The Content In React Markdown

Return your JSX code


return (

    <ReactMarkdown>{content}</ReactMarkdown>

  )

Add Syntax Highlighting For Code Blocks

So far, we have allowed Next.js to read markdown and convert it into JSX. However, the syntax highlighting isnt activated for code blocks.

We first need to inport the highlighter

import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { darcula } from "react-syntax-highlighter/dist/cjs/styles/prism";

Finally, we need to add the syntax configuration. Change your ReactMarkdown code block to this:

<ReactMarkdown
				components={{
					code({ node, inline, className, children, ref, ...props }) {
						const match = /language-(\w+)/.exec(className || "");

						return !inline && match ? (
							<SyntaxHighlighter style={darcula} language={match[1]} {...props}>
								{String(children).replace(/\n$/, "")}
							</SyntaxHighlighter>
						) : (
							<code className={className}>{children}</code>
						);
					},
				}}
			>