How to import and display Markdown files in React

Wed Sep 01 2021

tags: public programming webdev howto

Recently I found myself in need of importing and displaying long documents in a React SPA, but I didn't know how to do it. I combined the answers in these StackOverflow questions here ( 1, 2).

Three simple steps:

First, install React Markdown with yarn add react-markdown or your preferred package manager.

Then, declare a markdown.d.ts file and put it in your folder (I believe anywhere that Typescript can see is OK):

declare module '*.md' {
const value: string; // markdown is just a string
export default value;
}

You can then import Markdown files, fetch them, and parse them into a string. Pass the parsed Markdown file into the ReactMarkdown component, which takes in a children: string prop. You can use the useState and useEffect hooks to do this cleanly:

import { useState, useEffect } from 'react'
import ReactMarkdown from 'react-markdown'

// Terms of Use and Privacy Policy
import TermsOfUse from './texts/terms_of_use.md'
import PrivacyPolicy from './texts/privacy_policy.md'

export const TermsPage = (): JSX.Element => {
const [tosText, setTosText] = useState('')
const [privacyPolicyText, setPrivacyPolicyText] = useState('')

// Fetch Terms of Use
useEffect(() => {
fetch(TermsOfUse).then(res => res.text()).then(text => setTosText(text))
})

useEffect(() => {
fetch(PrivacyPolicy).then(res => res.text()).then(text => setPrivacyPolicyText(text))
})

return (
<div>
<ReactMarkdown children={tosText} />
<ReactMarkdown children={privacyPolicyText} />
</div>
)
}

This means you could probably use ReactMarkdown + Router for your blog instead of a static site generator. Maintain a map of routes to Markdown files and fetch the file when the user navigates to the chosen route. Maybe (most probably) I've just reinvented the wheel, lol.