by Timur Dautov

How to Render Markdown in React

To render Markdown in React, you can use the react-markdown library.

Libraries to Render Markdown in React#

  • react-markdown: A markdown parser and renderer
  • remark: A framework for processing Markdown
  • rehype: A framework for processing HTML
  • gray-matter: Parses frontmatter (YAML metadata) from Markdown files
  • remark-gfm: Enables GitHub Flavored Markdown (GFM) support
  • remark-emoji: Enables emoji support in Markdown
  • remark-autolink-headings: Automatically creates anchor links for headings
  • remark-toc: Generates Table of Contents (TOC) from headings
  • remark-collapse: Collapsible sections in Markdown
  • remark-math: Enables Math support in Markdown
  • rehype-katex: Renders Math equations using KaTeX
  • rehype-pretty-code: Syntax highlighting for code blocks
  • rehype-external-links: Opens external links in new tabs

Render Markdown in React#

To render Markdown in React, you can use the react-markdown library.

import ReactMarkdown from 'react-markdown';

<ReactMarkdown>
  {markdown}
</ReactMarkdown>

Render MDX in React#

MDX is a superset of Markdown that allows you to write JSX and import other files.

To render MDX in React, you can use the @mdx-js/react library.

import { MDXProvider } from '@mdx-js/react';

<MDXProvider>
  <MDXContent />
</MDXProvider>

Add Syntax Highlighting#

To add syntax highlighting to your Markdown or MDX, you can use the rehype-pretty-code library.

import { remark } from 'remark';
import { rehype } from 'rehype';

<ReactMarkdown>
  {markdown}
</ReactMarkdown>

Add Frontmatter#

To add frontmatter to your Markdown or MDX, you can use the gray-matter library.

import { remark } from 'remark';
import { matter } from 'gray-matter';

const { content, data } = matter(markdown);

<ReactMarkdown>
  {content}
</ReactMarkdown>