Gathering detailed insights and metrics for react-markdown
Gathering detailed insights and metrics for react-markdown
Gathering detailed insights and metrics for react-markdown
Gathering detailed insights and metrics for react-markdown
npm install react-markdown
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
13,288 Stars
538 Commits
876 Forks
53 Watching
5 Branches
81 Contributors
Updated on 27 Nov 2024
Minified
Minified + Gzipped
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-2.9%
579,731
Compared to previous day
Last week
4.5%
3,089,331
Compared to previous week
Last month
12.4%
12,867,956
Compared to previous month
Last year
55.4%
136,232,516
Compared to previous year
10
2
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 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 three main reasons are that they often rely on dangerouslySetInnerHTML
,
have bugs with how they handle markdown, or don’t let you swap elements for
components.
react-markdown
builds a virtual DOM, so React only replaces what changed,
from a syntax tree.
That’s 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 16+), install with npm:
1npm install react-markdown
In Deno with esm.sh
:
1import Markdown from 'https://esm.sh/react-markdown@9'
In browsers with esm.sh
:
1<script type="module"> 2 import Markdown from 'https://esm.sh/react-markdown@9?bundle' 3</script>
A basic hello world:
1import React from 'react' 2import {createRoot} from 'react-dom/client' 3import Markdown from 'react-markdown' 4 5const markdown = '# Hi, *Pluto*!' 6 7createRoot(document.body).render(<Markdown>{markdown}</Markdown>)
1<h1> 2 Hi, <em>Pluto</em>! 3</h1>
Here is an example that shows how to use a plugin (remark-gfm
,
which adds support for footnotes, strikethrough, tables, tasklists and URLs
directly):
1import React from 'react' 2import {createRoot} from 'react-dom/client' 3import Markdown from 'react-markdown' 4import remarkGfm from 'remark-gfm' 5 6const markdown = `Just a link: www.nasa.gov.` 7 8createRoot(document.body).render( 9 <Markdown remarkPlugins={[remarkGfm]}>{markdown}</Markdown> 10)
1<p> 2 Just a link: <a href="http://www.nasa.gov">www.nasa.gov</a>. 3</p>
This package exports the following identifier:
defaultUrlTransform
.
The default export is Markdown
.
Markdown
Component to render markdown.
options
(Options
)
— propsReact element (JSX.Element
).
defaultUrlTransform(url)
Make a URL safe.
url
(string
)
— URLSafe URL (string
).
AllowElement
Filter elements (TypeScript type).
node
(Element
from hast
)
— element to checkindex
(number | undefined
)
— index of element
in parent
parent
(Node
from hast
)
— parent of element
Whether to allow element
(boolean
, optional).
Components
Map tag names to components (TypeScript type).
1import type {Element} from 'hast' 2 3type Components = Partial<{ 4 [TagName in keyof JSX.IntrinsicElements]: 5 // Class component: 6 | (new (props: JSX.IntrinsicElements[TagName] & ExtraProps) => JSX.ElementClass) 7 // Function component: 8 | ((props: JSX.IntrinsicElements[TagName] & ExtraProps) => JSX.Element | string | null | undefined) 9 // Tag name: 10 | keyof JSX.IntrinsicElements 11}>
ExtraProps
Extra fields we pass to components (TypeScript type).
node
(Element
from hast
, optional)
— original nodeOptions
Configuration (TypeScript type).
allowElement
(AllowElement
, optional)
— filter elements;
allowedElements
/ disallowedElements
is used firstallowedElements
(Array<string>
, default: all tag names)
— tag names to allow;
cannot combine w/ disallowedElements
children
(string
, optional)
— markdownclassName
(string
, optional)
— wrap in a div
with this class namecomponents
(Components
, optional)
— map tag names to componentsdisallowedElements
(Array<string>
, default: []
)
— tag names to disallow;
cannot combine w/ allowedElements
rehypePlugins
(Array<Plugin>
, optional)
— list of rehype plugins to useremarkPlugins
(Array<Plugin>
, optional)
— list of remark plugins to useremarkRehypeOptions
(Options
from
remark-rehype
, optional)
— options to pass through to remark-rehype
skipHtml
(boolean
, default: false
)
— ignore HTML in markdown completelyunwrapDisallowed
(boolean
, default: false
)
— extract (unwrap) what’s in disallowed elements;
normally when say strong
is not allowed, it and it’s children are dropped,
with unwrapDisallowed
the element itself is replaced by its childrenurlTransform
(UrlTransform
, default:
defaultUrlTransform
)
— change URLsUrlTransform
Transform URLs (TypeScript type).
url
(string
)
— URLkey
(string
, example: 'href'
)
— property namenode
(Element
from hast
)
— element to checkTransformed URL (string
, optional).
This example shows how to use a remark plugin.
In this case, remark-gfm
, which adds support for strikethrough,
tables, tasklists and URLs directly:
1import React from 'react' 2import {createRoot} from 'react-dom/client' 3import Markdown from 'react-markdown' 4import remarkGfm from 'remark-gfm' 5 6const markdown = `A paragraph with *emphasis* and **strong importance**. 7 8> A block quote with ~strikethrough~ and a URL: https://reactjs.org. 9 10* Lists 11* [ ] todo 12* [x] done 13 14A table: 15 16| a | b | 17| - | - | 18` 19 20createRoot(document.body).render( 21 <Markdown remarkPlugins={[remarkGfm]}>{markdown}</Markdown> 22)
1<> 2 <p> 3 A paragraph with <em>emphasis</em> and <strong>strong importance</strong>. 4 </p> 5 <blockquote> 6 <p> 7 A block quote with <del>strikethrough</del> and a URL:{' '} 8 <a href="https://reactjs.org">https://reactjs.org</a>. 9 </p> 10 </blockquote> 11 <ul className="contains-task-list"> 12 <li>Lists</li> 13 <li className="task-list-item"> 14 <input type="checkbox" disabled /> todo 15 </li> 16 <li className="task-list-item"> 17 <input type="checkbox" disabled checked /> done 18 </li> 19 </ul> 20 <p>A table:</p> 21 <table> 22 <thead> 23 <tr> 24 <th>a</th> 25 <th>b</th> 26 </tr> 27 </thead> 28 </table> 29</>
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:
1import React from 'react' 2import {createRoot} from 'react-dom/client' 3import Markdown from 'react-markdown' 4import remarkGfm from 'remark-gfm' 5 6const markdown = 'This ~is not~ strikethrough, but ~~this is~~!' 7 8createRoot(document.body).render( 9 <Markdown remarkPlugins={[[remarkGfm, {singleTilde: false}]]}> 10 {markdown} 11 </Markdown> 12)
1<p> 2 This ~is not~ strikethrough, but <del>this is</del>! 3</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:
1import React from 'react' 2import {createRoot} from 'react-dom/client' 3import Markdown from 'react-markdown' 4import {Prism as SyntaxHighlighter} from 'react-syntax-highlighter' 5import {dark} from 'react-syntax-highlighter/dist/esm/styles/prism' 6 7// Did you know you can use tildes instead of backticks for code in markdown? ✨ 8const markdown = `Here is some JavaScript code: 9 10~~~js 11console.log('It works!') 12~~~ 13` 14 15createRoot(document.body).render( 16 <Markdown 17 children={markdown} 18 components={{ 19 code(props) { 20 const {children, className, node, ...rest} = props 21 const match = /language-(\w+)/.exec(className || '') 22 return match ? ( 23 <SyntaxHighlighter 24 {...rest} 25 PreTag="div" 26 children={String(children).replace(/\n$/, '')} 27 language={match[1]} 28 style={dark} 29 /> 30 ) : ( 31 <code {...rest} className={className}> 32 {children} 33 </code> 34 ) 35 } 36 }} 37 /> 38)
1<> 2 <p>Here is some JavaScript code:</p> 3 <pre> 4 <SyntaxHighlighter language="js" style={dark} PreTag="div" children="console.log('It works!')" /> 5 </pre> 6</>
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.
1import React from 'react' 2import {createRoot} from 'react-dom/client' 3import Markdown from 'react-markdown' 4import rehypeKatex from 'rehype-katex' 5import remarkMath from 'remark-math' 6import 'katex/dist/katex.min.css' // `rehype-katex` does not import the CSS for you 7 8const markdown = `The lift coefficient ($C_L$) is a dimensionless coefficient.` 9 10createRoot(document.body).render( 11 <Markdown remarkPlugins={[remarkMath]} rehypePlugins={[rehypeKatex]}> 12 {markdown} 13 </Markdown> 14)
1<p> 2 The lift coefficient ( 3 <span className="katex"> 4 <span className="katex-mathml"> 5 <math xmlns="http://www.w3.org/1998/Math/MathML">{/* … */}</math> 6 </span> 7 <span className="katex-html" aria-hidden="true"> 8 {/* … */} 9 </span> 10 </span> 11 ) is a dimensionless coefficient. 12</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 the additional types
AllowElement
,
ExtraProps
,
Components
,
Options
, and
UrlTransform
.
Projects maintained by the unified collective are compatible with maintained versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line, react-markdown@^9
,
compatible with Node.js 16.
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
:
1import React from 'react' 2import {createRoot} from 'react-dom/client' 3import Markdown from 'react-markdown' 4import rehypeRaw from 'rehype-raw' 5 6const markdown = `<div class="note"> 7 8Some *emphasis* and <strong>strong</strong>! 9 10</div>` 11 12createRoot(document.body).render( 13 <Markdown rehypePlugins={[rehypeRaw]}>{markdown}</Markdown> 14)
1<div className="note"> 2 <p> 3 Some <em>emphasis</em> and <strong>strong</strong>! 4 </p> 5</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:
1<Markdown 2 components={{ 3 // Map `h1` (`# heading`) to use `h2`s. 4 h1: 'h2', 5 // Rewrite `em`s (`*like so*`) to `i` with a red foreground color. 6 em(props) { 7 const {node, ...rest} = props 8 return <i style={{color: 'red'}} {...rest} /> 9 } 10 }} 11/>
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
, alt
and title
,
etc.
Every component will receive a node
.
This is the original Element
from hast
element being turned
into a React element.
You might have trouble with how line endings work in markdown and JSX. We recommend the following, which solves all line ending problems:
1// If you write actual markdown in your code, put your markdown in a variable; 2// **do not indent markdown**: 3const markdown = ` 4# This is perfect! 5` 6 7// Pass the value as an expression as an only child: 8const result = <Markdown>{markdown}</Markdown>
👆 That works. Read on for what doesn’t and why that is.
You might try to write markdown directly in your JSX and find that it does not work:
1<Markdown> 2 # Hi 3 4 This is **not** a paragraph. 5</Markdown>
The is because in JSX the whitespace (including line endings) is collapsed to a single space. So the above example is equivalent to:
1<Markdown> # Hi This is **not** a paragraph. </Markdown>
Instead, to pass markdown to Markdown
, you can use an expression:
with a template literal:
1<Markdown>{` 2# Hi 3 4This is a paragraph. 5`}</Markdown>
Template literals have another potential problem, because they keep whitespace (including indentation) inside them. That means that the following does not turn into a heading:
1<Markdown>{` 2 # This is **not** a heading, it’s an indented code block 3`}</Markdown>
Use of react-markdown
is secure by default.
Overwriting urlTransform
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
— 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.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
10 commit(s) and 18 issue activity found in the last 90 days -- score normalized to 10
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
Found 5/30 approved changesets -- score normalized to 1
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More