Introduction
react-markdown is a React component that converts markdown strings into React elements. Unlike dangerouslySetInnerHTML, it parses markdown into an AST and renders it as proper React components, which is safe by default against XSS. It is built on the unified/remark ecosystem and supports plugins for GFM tables, syntax highlighting, math, and more.
What react-markdown Does
- Renders markdown strings as React elements without
dangerouslySetInnerHTML - Sanitizes output by default since HTML is not passed through
- Supports remark and rehype plugins for extended syntax
- Allows custom component mapping for any HTML element
- Handles GFM (tables, task lists, strikethrough) via
remark-gfmplugin
Architecture Overview
react-markdown uses remark to parse markdown into an mdast (markdown AST), then rehype to convert it into an hast (HTML AST), and finally renders the hast nodes as React elements. Each AST transformation step can be extended with plugins. The components prop lets you map HTML tag names to custom React components, giving full control over rendering without touching the parser.
Self-Hosting & Configuration
- Install via npm:
npm install react-markdown - Add GFM support:
npm install remark-gfmthen pass as plugin - Map custom components:
<Markdown components={{ h1: MyHeading, a: MyLink }}> - Add syntax highlighting with
rehype-highlightorreact-syntax-highlighter - Enable raw HTML pass-through (unsafe) with
rehype-rawwhen trusted content requires it
Key Features
- Safe by default: no HTML injection without explicit opt-in
- Plugin ecosystem via remark (markdown) and rehype (HTML) transformers
- Component overrides for full rendering control
- GFM support including tables, task lists, footnotes, and autolinks
- Lightweight with tree-shaking support
Comparison with Similar Tools
- markdown-it — returns raw HTML strings, needs
dangerouslySetInnerHTML - marked — fast HTML string output, no React element tree
- MDX — compiles markdown with JSX at build time, different use case
- Markdoc — Stripe's markdown toolkit, more opinionated, tag-based extensions
- next-mdx-remote — for rendering MDX in Next.js with dynamic content
FAQ
Q: How do I add syntax highlighting to code blocks?
A: Use a custom code component with react-syntax-highlighter, or add rehype-highlight as a rehype plugin.
Q: Is react-markdown safe from XSS?
A: Yes, by default raw HTML in markdown is ignored. Only use rehype-raw with trusted content.
Q: Can I render markdown from a CMS or API?
A: Yes, pass the markdown string as children to the <Markdown> component. It renders at runtime, no build step needed.
Q: How do I add GFM table support?
A: Install remark-gfm and pass it: <Markdown remarkPlugins={[remarkGfm]}>.