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.
There 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.
Install
This package is ESM only.
In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:
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):
importReactfrom'react'importReactDomfrom'react-dom'importReactMarkdownfrom'react-markdown'importremarkGfmfrom'remark-gfm'constmarkdown=`Just a link: https://reactjs.com.`ReactDom.render(<ReactMarkdownchildren={markdown}remarkPlugins={[remarkGfm]}/>,document.body)
Show equivalent JSX
<p>
Just a link: <ahref="https://reactjs.com">https://reactjs.com</a>.
</p>
API
This package exports the following identifier:
uriTransformer.
The default export is ReactMarkdown.
props
children (string, default: '')
markdown to parse
components (Record<string, Component>, default: {})
object mapping tag names to React components
remarkPlugins (Array<Plugin>, default: [])
list of remark plugins to use
rehypePlugins (Array<Plugin>, default: [])
list of rehype plugins to use
remarkRehypeOptions (Object?, default: undefined)
options to pass through to remark-rehype
className (string?)
wrap the markdown in a div with this class name
skipHtml (boolean, default: false)
ignore HTML in markdown completely
sourcePos (boolean, default: false)
pass a prop to all components with a serialized position
(data-sourcepos="3:1-3:13")
rawSourcePos (boolean, default: false)
pass a prop to all components with their position
(sourcePosition: {start: {line: 3, column: 1}, end:…})
includeElementIndex (boolean, default: false)
pass the index (number of elements before it) and siblingCount (number
of elements in parent) as props to all components
allowedElements (Array<string>, default: undefined)
tag names to allow (can’t combine w/ disallowedElements), all tag names
are allowed by default
disallowedElements (Array<string>, default: undefined)
tag names to disallow (can’t combine w/ allowedElements), all tag names
are allowed by default
allowElement ((element, index, parent) => boolean?, optional)
function called to check if an element is allowed (when truthy) or not,
allowedElements or disallowedElements is used first!
unwrapDisallowed (boolean, default: false)
extract (unwrap) the children of not allowed elements, by default, when
strong is disallowed, it and it’s children are dropped, but with
unwrapDisallowed the element itself is replaced by its children
linkTarget (string or (href, children, title) => string, optional)
target to use on links (such as _blank for <a target="_blank"…)
transformLinkUri ((href, children, title) => string, default:
uriTransformer, optional)
change URLs on links, pass null to allow all URLs, see security
transformImageUri ((src, alt, title) => string, default:
uriTransformer, optional)
change URLs on images, pass null to allow all URLs, see security
uriTransformer
Our 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).
This example shows how to use a remark plugin.
In this case, remark-gfm, which adds support for strikethrough, tables,
tasklists and URLs directly:
importReactfrom'react'importReactMarkdownfrom'react-markdown'importReactDomfrom'react-dom'importremarkGfmfrom'remark-gfm'constmarkdown=`A paragraph with *emphasis* and **strong importance**.> A block quote with ~strikethrough~ and a URL: https://reactjs.org.* Lists* [ ] todo* [x] doneA table:| a | b || - | - |`ReactDom.render(<ReactMarkdownchildren={markdown}remarkPlugins={[remarkGfm]}/>,document.body)
Show equivalent JSX
<><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:{' '}<ahref="https://reactjs.org">https://reactjs.org</a>.
</p></blockquote><ul><li>Lists</li><li><inputchecked={false}readOnly={true}type="checkbox"/> todo
</li><li><inputchecked={true}readOnly={true}type="checkbox"/> done
</li></ul><p>A table:</p><table><thead><tr><td>a</td><td>b</td></tr></thead></table></>
Use a plugin with options
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:
importReactfrom'react'importReactMarkdownfrom'react-markdown'importReactDomfrom'react-dom'importremarkGfmfrom'remark-gfm'ReactDom.render(<ReactMarkdownremarkPlugins={[[remarkGfm,{singleTilde: false}]]}>
This ~is not~ strikethrough, but ~~this is~~!
</ReactMarkdown>,document.body)
Show equivalent JSX
<p>
This ~is not~ strikethrough, but <del>this is</del>!
</p>
Use custom components (syntax highlight)
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:
importReactfrom'react'importReactDomfrom'react-dom'importReactMarkdownfrom'react-markdown'import{PrismasSyntaxHighlighter}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? ✨constmarkdown=`Here is some JavaScript code:~~~jsconsole.log('It works!')~~~`ReactDom.render(<ReactMarkdownchildren={markdown}components={{code({node, inline, className, children, ...props}){constmatch=/language-(\w+)/.exec(className||'')return!inline&&match ? (<SyntaxHighlighterchildren={String(children).replace(/\n$/,'')}style={dark}language={match[1]}PreTag="div"{...props}/>) : (<codeclassName={className}{...props}>{children}</code>)}}}/>,document.body)
Show equivalent JSX
<><p>Here is some JavaScript code:</p><pre><SyntaxHighlighterlanguage="js"style={dark}PreTag="div"children="console.log('It works!')"/></pre></>
Use remark and rehype plugins (math)
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.
importReactfrom'react'importReactDomfrom'react-dom'importReactMarkdownfrom'react-markdown'importremarkMathfrom'remark-math'importrehypeKatexfrom'rehype-katex'import'katex/dist/katex.min.css'// `rehype-katex` does not import the CSS for youReactDom.render(<ReactMarkdownchildren={`The lift coefficient ($C_L$) is a dimensionless coefficient.`}remarkPlugins={[remarkMath]}rehypePlugins={[rehypeKatex]}/>,document.body)
Show equivalent JSX
<p>
The lift coefficient (
<spanclassName="math math-inline"><spanclassName="katex"><spanclassName="katex-mathml"><mathxmlns="http://www.w3.org/1998/Math/MathML">{/* … */}</math></span><spanclassName="katex-html"aria-hidden="true">{/* … */}</span></span></span>
) is a dimensionless coefficient.
</p>
Plugins
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:
react-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.
Types
This package is fully typed with TypeScript.
It exports Options and Components types, which specify the interface of the
accepted props and components.
Compatibility
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.
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:
parse markdown to mdast (markdown syntax tree)
transform through remark (markdown ecosystem)
transform mdast to hast (HTML syntax tree)
transform through rehype (HTML ecosystem)
render hast to React with components
Appendix A: HTML in markdown
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
请发表评论