Introduction
There are several Markdown libraries available, and this time I'll introduce Next/MDX.
I've used react-markdown with React before, but I personally didn't prefer it.
I had some requirements such as being able to combine variables or easily insert images, rather than just using plain Markdown.
Meeting these requirements can make things a bit complex.
In such cases, "Next/MDX" meets those needs and allows for clean, smart syntax, so I chose to try it.
Here’s how to add it to your project and render content.
Environment
- Next.js: 14.0.3
Steps
Install Required Packages
To render @next/mdx, several packages are needed.
Add them to your project using the following command:
npm install @next/mdx @mdx-js/loader @mdx-js/react @types/mdx
Add to Configuration File (next.config.js)
Set it up like this:
// next.config.js
const withMDX = require('@next/mdx')()
const nextConfig = {
// omitted
};
module.exports = withMDX(nextConfig);
withMDX
is a plugin that supports Markdown and React to configure MDX.
By writing withMDX(nextConfig)
, MDX files are integrated into the build process.
Create an MDX File
Create src/component/md.mdx:
# Welcome to my MDX page!
This is some **bold** and _italics_ text.
This is a list in markdown:
- One
- Two
- Three
Import into TSX
Create src/app/page.tsx:
"use client"
import Mdx from '@/component/md.mdx'
const App = () => {
return (
<>
<Mdx />
</>
);
}
export default App;
This way, the Markdown will be rendered as HTML and displayed.
Since we’re using the App Router, "use client"
is added at the top.
References
Conclusion
The setup is simple and it's easy to use.
It’s a popular library, so there are many helpful references available.
It also seems usable with other frameworks, making it quite versatile.