react-markdown
Markdown component for React using remark.
Learn markdown here and check out the demo here.
Install
npm:
npm install react-markdown
Why this one?
There are other ways for 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 (optionally GFM) compliant and has extensions to support custom syntax.
Use
A basic hello world:
import React from 'react'
import ReactMarkdown from 'react-markdown'
import {render} from 'react-dom'
render(<ReactMarkdown># Hello, *world*!</ReactMarkdown>, document.body)
Show equivalent JSX
<h1>
Hello, <em>world</em>!
</h1>
Here is an example using require
s, passing the markdown as a string, and how to use a plugin (remark-gfm
, which adds support for strikethrough, tables, tasklists and URLs directly):
const React = require('react')
const ReactMarkdown = require('react-markdown')
const render = require('react-dom').render
const gfm = require('remark-gfm')
const markdown = `Just a link: https://reactjs.com.`
render(<ReactMarkdown plugins={[gfm]} children={markdown} />, document.body)
Show equivalent JSX
<p>
Just a link: <a href="https://reactjs.com">https://reactjs.com</a>.
</p>
API
props
children
(string
, default:''
)
Markdown to parseclassName
(string?
)
Wrap the markdown in adiv
with this class nameallowDangerousHtml
(boolean
, default:false
)
This project is safe by default and escapes HTML. UseallowDangerousHtml: true
to allow dangerous html instead. See securityskipHtml
(boolean
, default:false
)
Ignore HTML in MarkdownsourcePos
(boolean
, default:false
)
Pass a prop to all renderers with a serialized position (data-sourcepos="3:1-3:13"
)rawSourcePos
(boolean
, default:false
)
Pass a prop to all renderers with their position (sourcePosition: {start: {line: 3, column: 1}, end:…}
)includeNodeIndex
(boolean
, default:false
)
Passindex
andparentChildCount
in props to all renderersallowedTypes
(Array.<string>
, default: list of all types)
Node types to allow (can’t combine w/disallowedTypes
). All types are available atReactMarkdown.types
disallowedTypes
(Array.<string>
, default:[]
)
Node types to disallow (can’t combine w/allowedTypes
)allowNode
((node, index, parent) => boolean?
, optional)
Function called to check if a node is allowed (when truthy) or not.allowedTypes
/disallowedTypes
is used first!unwrapDisallowed
(boolean
, default:false
)
Extract (unwrap) the children of not allowed nodes. By default, whenstrong
is not allowed, it and it’s content is dropped, but withunwrapDisallowed
the node itself is dropped but the content usedlinkTarget
(string
or(url, text, title) => string
, optional)
Target to use on links (such as_blank
for<a target="_blank"…
)transformLinkUri
((uri) => string
, default:./uri-transformer.js
, optional)
URL to use for links. The default allows onlyhttp
,https
,mailto
, andtel
, and is available atReactMarkdown.uriTransformer
. Passnull
to allow all URLs. See securitytransformImageUri
((uri) => string
, default:./uri-transformer.js
, optional)
Same astransformLinkUri
but for imagesrenderers
(Object.<Component>
, default:{}
)
Object mapping node types to React components. Merged with the default renderers (available atReactMarkdown.renderers
). Which props are passed varies based on the nodeplugins
(Array.<Plugin>
, default:[]
)
List of remark plugins to use. See the next section for examples on how to pass options
Examples
Use a plugin
This example shows how to use a 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 {render} from 'react-dom'
import gfm 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 |
| - | - |
`
render(<ReactMarkdown plugins={[gfm]} children={markdown} />, 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:{' '}
<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>
</>
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:
import React from 'react'
import ReactMarkdown from 'react-markdown'
import {render} from 'react-dom'
import gfm from 'remark-gfm'
render(
<ReactMarkdown plugins={[[gfm, {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 renderers (syntax highlight)
This example shows how you can overwrite the normal handling of a node by passing a renderer. In this case, we apply syntax highlighting with the seriously super amazing react-syntax-highlighter
by @conorhastings:
import React from 'react'
import ReactMarkdown from 'react-markdown'
import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter'
import {dark} from 'react-syntax-highlighter/dist/esm/styles/prism'
import {render} from 'react-dom'
const renderers = {
code: ({language, value}) => {
return <SyntaxHighlighter style={dark} language={language} children={value} />
}
}
// 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!')
~~~
`
render(<ReactMarkdown renderers={renderers} children={markdown} />, document.body)
Show equivalent JSX
<>
<p>Here is some JavaScript code:</p>
<SyntaxHighlighter language="js" style={dark} children="console.log('It works!')" />
</>
Use a plugin and custom renderers (math)
This example shows how a syntax extension is used to support math in markdown that adds new node types (remark-math
), which are then handled by renderers to use @matejmazur/react-katex
:
import React from 'react'
import ReactMarkdown from 'react-markdown'
import Tex from '@matejmazur/react-katex'
import {render} from 'react-dom'
import math from 'remark-math'
import 'katex/dist/katex.min.css' // `react-katex` does not import the CSS for you
const renderers = {
inlineMath: ({value}) => <Tex math={value} />,
math: ({value}) => <Tex block math={value} />
}
render(
<ReactMarkdown
plugins={[math]}
renderers={renderers}
children={`The lift coefficient ($C_L$) is a dimensionless coefficient.`}
/>,
document.body
)
Show equivalent JSX
<p>
The lift coefficient (<Tex math="C_L" />) is a dimensionless coefficient.
</p>
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), you can react-markdown/with-html
:
const React = require('react')
const ReactMarkdownWithHtml = require('react-markdown/with-html')
const render = require('react-dom').render
const markdown = `
This Markdown contains <a href="https://en.wikipedia.org/wiki/HTML">HTML</a>, and will require the <code>html-parser</code> AST plugin to be loaded, in addition to setting the <code class="prop">allowDangerousHtml</code> property to false.
`
render(<ReactMarkdownWithHtml children={markdown} allowDangerousHtml />, document.body)
Show equivalent JSX
<p>
This Markdown contains <a href="https://en.wikipedia.org/wiki/HTML">HTML</a>, and will require
the <code>html-parser</code> AST plugin to be loaded, in addition to setting the{' '}
<code className="prop">allowDangerousHtml</code> property to false.
</p>
If you want to specify options for the HTML parsing step, you can instead import the extension directly:
const ReactMarkdown = require('react-markdown')
const htmlParser = require('react-markdown/plugins/html-parser')
// For more info on the processing instructions, see
// <https://github.com/aknuds1/html-to-react#with-custom-processing-instructions>
const parse = htmlParser({
isValidNode: (node) => node.type !== 'script',
processingInstructions: [/* ... */]
})
<ReactMarkdown htmlParser={parse} allowDangerousHtml children={markdown} />
Appendix B: Node types
The node types available by default are:
root
— Whole documenttext
— Text (foo
)break
— Hard break (<br>
)paragraph
— Paragraph (<p>
)emphasis
— Emphasis (<em>
)strong
— Strong (<strong>
)thematicBreak
— Horizontal rule (<hr>
)blockquote
— Block quote (<blockquote>
)link
— Link (<a>
)image
— Image (<img>
)linkReference
— Link through a reference (<a>
)imageReference
— Image through a reference (<img>
)list
— List (<ul>
or<ol>
)listItem
— List item (<li>
)definition
— Definition for a reference (not rendered)heading
— Heading (<h1>
through<h6>
)inlineCode
— Inline code (<code>
)code
— Block of code (<pre><code>
)html
— HTML node (Best-effort rendering)virtualHtml
— IfallowDangerousHtml
is not on andskipHtml
is off, a naive HTML parser is used to support basic HTMLparsedHtml
— IfallowDangerousHtml
is on,skipHtml
is off, andhtml-parser
is used, more advanced HTML is supported
With remark-gfm
, the following are also available:
delete
— Delete text (<del>
)table
— Table (<table>
)tableHead
— Table head (<thead>
)tableBody
— Table body (<tbody>
)tableRow
— Table row (<tr>
)tableCell
— Table cell (<td>
or<th>
)
Security
Use of react-markdown
is secure by default. Overwriting transformLinkUri
or transformImageUri
to something insecure or turning allowDangerousHtml
on, will open you up to XSS vectors. Furthermore, the plugins
you use and renderers
you write may be insecure.
Related
MDX
— JSX in markdownremark-gfm
— Plugin for GitHub flavored markdown support
Contribute
See 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.