I’m working on a little website and I wanted to store some markdown files in a /content folder which allows a user to create their content as markdown without ever needing to change the website – think of this as a very simple file based CMS.
So the idea is we use git to handle versioning via revisions. The user can just change their markdown files for their content and the website will rebuild in something like GitHub actions and the content is then used by the site.
Depending on what we’re doing we’ve got a couple of options to include the markdown.
The first is simply import the markdown file using
import contactContent from '../../content/contact.md?raw';
export default function Contact() {
return (
<div>
{contactContent}
</div>
);
}
The ?raw informs Vite or the likes to not try to parse this file, just supply it as raw text as a string.
This is fine if you’re just reading the test but if you want to render markdown you can use react-markdown.
Add the package (and the vite-plugin-markdown) using
npm install react-markdown npm install vite-plugin-markdown
You’ll likely want these plugins as well
npm install rehype-raw npm install remark-gfm
Now we can use the ReactMarkdown component like this
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeRaw]}
>
{content}
</ReactMarkdown>
In this example we’d import the markdown as we did earlier, in this can we’re passing by props (potentially) as a content string.
In my case, I’m using Vite, and the import with the ?raw tells the Vite tooling to essentially treat this as a plain text file and it’ll get bundled and hence not visible in the dist folder. This is great because we can change the markdown and hot reload will update redisplay the changes.