$ cnpm install react-markdown
React component to render markdown.
dangerouslySetInnerHTML or XSS attacks)<h2> for ## hi)This package is a React component that can be given a string of markdown that it’ll safely render to React elements. You can pass plugins to change how markdown is transformed to React elements and pass components that will be used instead of normal HTML elements.
react-markdown, see our demoThere are other ways to use markdown in React out there so why use this one?
The two main reasons are that they often rely on dangerouslySetInnerHTML or
have bugs with how they handle markdown.
react-markdown uses a syntax tree to build the virtual dom which allows for
updating only the changing DOM instead of completely overwriting.
react-markdown is 100% CommonMark compliant and has plugins to support other
syntax extensions (such as GFM).
These features are supported because we use unified, specifically remark for markdown and rehype for HTML, which are popular tools to transform content with plugins.
This package focusses on making it easy for beginners to safely use markdown in
React.
When you’re familiar with unified, you can use a modern hooks based alternative
react-remark or rehype-react manually.
If you instead want to use JavaScript and JSX inside markdown files, use
MDX.
This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:
npm install react-markdown
In Deno with esm.sh:
import ReactMarkdown from 'https://esm.sh/react-markdown@7'
In browsers with esm.sh:
<script type="module">
import ReactMarkdown from 'https://esm.sh/react-markdown@7?bundle'
</script>
A basic hello world:
import React from 'react'
import ReactMarkdown from 'react-markdown'
import ReactDom from 'react-dom'
ReactDom.render(<ReactMarkdown># Hello, *world*!</ReactMarkdown>, document.body)
<h1>
Hello, <em>world</em>!
</h1>
Here is an example that shows passing the markdown as a string and how
to use a plugin (remark-gfm, which adds support for strikethrough,
tables, tasklists and URLs directly):
import React from 'react'
import ReactDom from 'react-dom'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
const markdown = `Just a link: https://reactjs.com.`
ReactDom.render(
<ReactMarkdown children={markdown} remarkPlugins={[remarkGfm]} />,
document.body
)
<p>
Just a link: <a href="https://reactjs.com">https://reactjs.com</a>.
</p>
This package exports the following identifier:
uriTransformer.
The default export is ReactMarkdown.
propschildren (string, default: '')components (Record<string, Component>, default: {})remarkPlugins (Array<Plugin>, default: [])rehypePlugins (Array<Plugin>, default: [])remarkRehypeOptions (Object?, default: undefined)remark-rehypeclassName (string?)div with this class nameskipHtml (boolean, default: false)sourcePos (boolean, default: false)data-sourcepos="3:1-3:13")rawSourcePos (boolean, default: false)sourcePosition: {start: {line: 3, column: 1}, end:…})includeElementIndex (boolean, default: false)index (number of elements before it) and siblingCount (number
of elements in parent) as props to all componentsallowedElements (Array<string>, default: undefined)disallowedElements), all tag names
are allowed by defaultdisallowedElements (Array<string>, default: undefined)allowedElements), all tag names
are allowed by defaultallowElement ((element, index, parent) => boolean?, optional)allowedElements or disallowedElements is used first!unwrapDisallowed (boolean, default: false)strong is disallowed, it and it’s children are dropped, but with
unwrapDisallowed the element itself is replaced by its childrenlinkTarget (string or (href, children, title) => string, optional)_blank for <a target="_blank"…)transformLinkUri ((href, children, title) => string, default:
uriTransformer, optional)null to allow all URLs, see securitytransformImageUri ((src, alt, title) => string, default:
uriTransformer, optional)null to allow all URLs, see securityuriTransformerOur default URL transform, which you can overwrite (see props above).
It’s given a URL and cleans it, by allowing only http:, https:, mailto:,
and tel: URLs, absolute paths (/example.png), and hashes (#some-place).
See the source code here.
This example shows how to use a remark plugin.
In this case, remark-gfm, which adds support for strikethrough, tables,
tasklists and URLs directly:
import React from 'react'
import ReactMarkdown from 'react-markdown'
import ReactDom from 'react-dom'
import remarkGfm from 'remark-gfm'
const markdown = `A paragraph with *emphasis* and **strong importance**.
> A block quote with ~strikethrough~ and a URL: https://reactjs.org.
* Lists
* [ ] todo
* [x] done
A table:
| a | b |
| - | - |
`
ReactDom.render(
<ReactMarkdown children={markdown} remarkPlugins={[remarkGfm]} />,
document.body
)
<>
<p>
A paragraph with <em>emphasis</em> and <strong>strong importance</strong>.
</p>
<blockquote>
<p>
A block quote with <del>strikethrough</del> and a URL:{' '}
<a href="https://reactjs.org">https://reactjs.org</a>.
</p>
</blockquote>
<ul>
<li>Lists</li>
<li>
<input checked={false} readOnly={true} type="checkbox" /> todo
</li>
<li>
<input checked={true} readOnly={true} type="checkbox" /> done
</li>
</ul>
<p>A table:</p>
<table>
<thead>
<tr>
<td>a</td>
<td>b</td>
</tr>
</thead>
</table>
</>
This example shows how to use a plugin and give it options.
To do that, use an array with the plugin at the first place, and the options
second.
remark-gfm has an option to allow only double tildes for strikethrough:
import React from 'react'
import ReactMarkdown from 'react-markdown'
import ReactDom from 'react-dom'
import remarkGfm from 'remark-gfm'
ReactDom.render(
<ReactMarkdown remarkPlugins={[[remarkGfm, {singleTilde: false}]]}>
This ~is not~ strikethrough, but ~~this is~~!
</ReactMarkdown>,
document.body
)
<p>
This ~is not~ strikethrough, but <del>this is</del>!
</p>
This example shows how you can overwrite the normal handling of an element by
passing a component.
In this case, we apply syntax highlighting with the seriously super amazing
react-syntax-highlighter by
@conorhastings:
import React from 'react'
import ReactDom from 'react-dom'
import ReactMarkdown from 'react-markdown'
import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'
import {dark} from 'react-syntax-highlighter/dist/esm/styles/prism'
// Did you know you can use tildes instead of backticks for code in markdown? ✨
const markdown = `Here is some JavaScript code:
~~~js
console.log('It works!')
~~~
`
ReactDom.render(
<ReactMarkdown
children={markdown}
components={{
code({node, inline, className, children, ...props}) {
const match = /language-(\w+)/.exec(className || '')
return !inline && match ? (
<SyntaxHighlighter
children={String(children).replace(/\n$/, '')}
style={dark}
language={match[1]}
PreTag="div"
{...props}
/>
) : (
<code className={className} {...props}>
{children}
</code>
)
}
}}
/>,
document.body
)
<>
<p>Here is some JavaScript code:</p>
<pre>
<SyntaxHighlighter language="js" style={dark} PreTag="div" children="console.log('It works!')" />
</pre>
</>
This example shows how a syntax extension (through remark-math)
is used to support math in markdown, and a transform plugin
(rehype-katex) to render that math.
import React from 'react'
import ReactDom from 'react-dom'
import ReactMarkdown from 'react-markdown'
import remarkMath from 'remark-math'
import rehypeKatex from 'rehype-katex'
import 'katex/dist/katex.min.css' // `rehype-katex` does not import the CSS for you
ReactDom.render(
<ReactMarkdown
children={`The lift coefficient ($C_L$) is a dimensionless coefficient.`}
remarkPlugins={[remarkMath]}
rehypePlugins={[rehypeKatex]}
/>,
document.body
)
<p>
The lift coefficient (
<span className="math math-inline">
<span className="katex">
<span className="katex-mathml">
<math xmlns="http://www.w3.org/1998/Math/MathML">{/* … */}</math>
</span>
<span className="katex-html" aria-hidden="true">
{/* … */}
</span>
</span>
</span>
) is a dimensionless coefficient.
</p>
We use unified, specifically remark for markdown and rehype for HTML, which are tools to transform content with plugins. Here are three good ways to find plugins:
awesome-remark and awesome-rehype
— selection of the most awesome projectsremark-plugin and rehype-plugin topics
— any tagged repo on GitHubreact-markdown follows CommonMark, which standardizes the differences between
markdown implementations, by default.
Some syntax extensions are supported through plugins.
We use micromark under the hood for our parsing.
See its documentation for more information on markdown, CommonMark, and
extensions.
This package is fully typed with TypeScript.
It exports Options and Components types, which specify the interface of the
accepted props and components.
Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed. They work in all modern browsers (essentially: everything not IE 11). You can use a bundler (such as esbuild, webpack, or Rollup) to use this package in your project, and use its options (or plugins) to add support for legacy browsers.
react-markdown
+----------------------------------------------------------------------------------------------------------------+
| |
| +----------+ +----------------+ +---------------+ +----------------+ +------------+ |
| | | | | | | | | | | |
markdown-+->+ remark +-mdast->+ remark plugins +-mdast->+ remark-rehype +-hast->+ rehype plugins +-hast->+ components +-+->react elements
| | | | | | | | | | | |
| +----------+ +----------------+ +---------------+ +----------------+ +------------+ |
| |
+----------------------------------------------------------------------------------------------------------------+
To understand what this project does, it’s important to first understand what
unified does: please read through the unifiedjs/unified readme (the
part until you hit the API section is required reading).
react-markdown is a unified pipeline — wrapped so that most folks don’t need
to directly interact with unified.
The processor goes through these steps:
react-markdown typically escapes HTML (or ignores it, with skipHtml)
because it is dangerous and defeats the purpose of this library.
However, if you are in a trusted environment (you trust the markdown), and
can spare the bundle size (±60kb minzipped), then you can use
rehype-raw:
import React from 'react'
import ReactDom from 'react-dom'
import ReactMarkdown from 'react-markdown'
import rehypeRaw from 'rehype-raw'
const input = `<div class="note">
Some *emphasis* and <strong>strong</strong>!
</div>`
ReactDom.render(
<ReactMarkdown rehypePlugins={[rehypeRaw]} children={input} />,
document.body
)
<div class="note">
<p>Some <em>emphasis</em> and <strong>strong</strong>!</p>
</div>
Note: HTML in markdown is still bound by how HTML works in CommonMark. Make sure to use blank lines around block-level HTML that again contains markdown!
You can also change the things that come from markdown:
<ReactMarkdown
components={{
// Map `h1` (`# heading`) to use `h2`s.
h1: 'h2',
// Rewrite `em`s (`*like so*`) to `i` with a red foreground color.
em: ({node, ...props}) => <i style={{color: 'red'}} {...props} />
}}
/>
The keys in components are HTML equivalents for the things you write with
markdown (such as h1 for # heading).
Normally, in markdown, those are: a, blockquote, br, code, em, h1,
h2, h3, h4, h5, h6, hr, img, li, ol, p, pre, strong, and
ul.
With remark-gfm, you can also use: del, input, table, tbody,
td, th, thead, and tr.
Other remark or rehype plugins that add support for new constructs will also
work with react-markdown.
The props that are passed are what you probably would expect: an a (link) will
get href (and title) props, and img (image) an src (and title), etc.
There are some extra props passed.
code
inline (boolean?)
— set to true for inline codeclassName (string?)
— set to language-js or so when using ```jsh1, h2, h3, h4, h5, h6
level (number between 1 and 6)
— heading rankinput (when using remark-gfm)
checked (boolean)
— whether the item is checkeddisabled (true)type ('checkbox')li
index (number)
— number of preceding items (so first gets 0, etc.)ordered (boolean)
— whether the parent is an ol or notchecked (boolean?)
— null normally, boolean when using remark-gfm’s tasklistsclassName (string?)
— set to task-list-item when using remark-gfm and the
item1 is a tasklistol, ul
depth (number)
— number of ancestral lists (so first gets 0, etc.)ordered (boolean)
— whether it’s an ol or notclassName (string?)
— set to contains-task-list when using remark-gfm and the
list contains one or more taskliststd, th (when using remark-gfm)
style (Object?)
— something like {textAlign: 'left'} depending on how the cell is
alignedisHeader (boolean)
— whether it’s a th or nottr (when using remark-gfm)
isHeader (boolean)
— whether it’s in the thead or notEvery component will receive a node (Object).
This is the original hast element being
turned into a React element.
Every element will receive a key (string).
See React’s docs for more
info.
Optionally, components will also receive:
data-sourcepos (string)
— see sourcePos optionsourcePosition (Object)
— see rawSourcePos optionindex and siblingCount (number)
— see includeElementIndex optiontarget on a (string)
— see linkTarget optionUse of react-markdown is secure by default.
Overwriting transformLinkUri or transformImageUri to something insecure will
open you up to XSS vectors.
Furthermore, the remarkPlugins, rehypePlugins, and components you use may
be insecure.
To make sure the content is completely safe, even after what plugins do,
use rehype-sanitize.
It lets you define your own schema of what is and isn’t allowed.
MDX
— JSX in markdownremark-gfm
— add support for GitHub flavored markdown supportreact-remark
— modern hook based alternativerehype-react
— turn HTML into React elementsSee contributing.md in remarkjs/.github for ways
to get started.
See support.md for ways to get help.
This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.
Copyright 2013 - present © cnpmjs.org