Security News
NIST Misses 2024 Deadline to Clear NVD Backlog
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
react-markdown
Advanced tools
The react-markdown npm package is a markdown renderer for React applications. It allows you to take Markdown content and render it as React components. This is useful for content-driven applications, such as blogs or documentation sites, where you want to allow content creators to write in Markdown and then display that content within your React application.
Rendering Markdown
This feature allows you to render standard Markdown text as React components. The example code shows how to import the ReactMarkdown component and use it to render a simple piece of Markdown text.
import React from 'react';
import ReactMarkdown from 'react-markdown';
const markdown = '# Hello, *world*!';
function App() {
return <ReactMarkdown>{markdown}</ReactMarkdown>;
}
export default App;
Custom Renderers
This feature allows you to define custom renderers for different Markdown elements. In the example, a custom renderer is provided for 'h1' elements, which renders them with a blue color.
import React from 'react';
import ReactMarkdown from 'react-markdown';
const markdown = '# Hello, *world*!';
function HeadingRenderer(props) {
return <h1 style={{ color: 'blue' }}>{props.children}</h1>;
}
function App() {
return (
<ReactMarkdown
components={{
h1: HeadingRenderer
}}
>
{markdown}
</ReactMarkdown>
);
}
export default App;
Inline HTML and Skip HTML
This feature allows you to include or exclude inline HTML within your Markdown content. The example code demonstrates how to skip rendering inline HTML by using the 'skipHtml' prop.
import React from 'react';
import ReactMarkdown from 'react-markdown';
const markdown = 'This is a paragraph with <span style="color: red;">inline HTML</span>.';
function App() {
return (
<ReactMarkdown skipHtml>
{markdown}
</ReactMarkdown>
);
}
export default App;
Plugins
This feature allows you to extend the functionality of react-markdown with plugins. The example code shows how to use the 'remark-gfm' plugin to add support for GitHub Flavored Markdown (GFM) task lists.
import React from 'react';
import ReactMarkdown from 'react-markdown';
import gfm from 'remark-gfm';
const markdown = 'This supports GitHub Flavored Markdown (GFM)\n\n- [ ] todo\n- [x] done';
function App() {
return <ReactMarkdown remarkPlugins={[gfm]}>{markdown}</ReactMarkdown>;
}
export default App;
Marked is a low-level markdown compiler for parsing markdown without caching or blocking for long periods of time. It is less React-specific than react-markdown and requires additional work to integrate with React.
Remarkable is a highly configurable markdown parser and compiler. It offers similar functionality to react-markdown but is not designed specifically for React and does not render React components out of the box.
markdown-to-jsx is another React component that lets you render Markdown as React components. It is similar to react-markdown but offers a simpler API with less configurability, which might be preferable for simpler use cases.
⚠️ Note: the below readme is for the upcoming release of react-markdown@6.0.0
.
See the last released readme (5.0.3
) here
»
Markdown component for React using remark.
Learn markdown here and check out the demo here.
npm:
npm install react-markdown
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.
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)
<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 remarkPlugins={[gfm]} children={markdown} />, document.body)
<p>
Just a link: <a href="https://reactjs.com">https://reactjs.com</a>.
</p>
props
children
(string
, default: ''
)className
(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
).
By default all elements are alloweddisallowedElements
(Array.<string>
, default: undefined
)allowedElements
).
By default no elements are disallowedallowElement
((element, index, parent) => boolean?
, optional)allowedElements
/ disallowedElements
is used first!unwrapDisallowed
(boolean
, default: false
)strong
is not allowed, it and it’s children is dropped,
but with unwrapDisallowed
the element itself is dropped but the children
usedlinkTarget
(string
or (href, children, title) => string
, optional)_blank
for <a target="_blank"…
)transformLinkUri
((href, children, title) => string
, default:
./uri-transformer.js
, optional)http
, https
, mailto
, and tel
, and is
available at ReactMarkdown.uriTransformer
.
Pass null
to allow all URLs.
See securitytransformImageUri
((src, alt, title) => string
, default:
./uri-transformer.js
, optional)transformLinkUri
but for imagescomponents
(Object.<string, Component>
, default: {}
)remarkPlugins
(Array.<Plugin>
, default: []
)rehypePlugins
(Array.<Plugin>
, default: []
)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 {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 remarkPlugins={[gfm]} children={markdown} />, 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 {render} from 'react-dom'
import gfm from 'remark-gfm'
render(
<ReactMarkdown remarkPlugins={[[gfm, {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 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 components = {
code({node, className, ...props}) {
const match = /language-(\w+)/.exec(className || '')
return match
? <SyntaxHighlighter language={match[1]} PreTag="div" style={dark} {...props} />
: <code className={className} {...props} />
}
}
// 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 components={components} children={markdown} />, 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 {render} 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
render(
<ReactMarkdown
remarkPlugins={[remarkMath]}
rehypePlugins={[rehypeKatex]}
children={`The lift coefficient ($C_L$) is a dimensionless coefficient.`}
/>,
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>
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 ReactMarkdown from 'react-markdown'
import rehypeRaw from 'rehype-raw'
import {render} from 'react-dom'
const input = `<div class="note">
Some *emphasis* and <strong>strong</strong>!
</div>`
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:
<Markdown
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
, 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 ```js
h1
, h2
, h3
, h4
, h5
, h6
level
(number
beween 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
and rehypePlugins
you use and components
you write may be insecure.
To make sure the content is completely safe, even after what plugins do,
use rehype-sanitize
.
That plugin lets you define your own schema of what is and isn’t allowed.
MDX
— JSX in markdownremark-gfm
— Plugin for GitHub flavored markdown supportSee 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.
6.0.0 - 2021-04-15
Welcome to version 6. This a major release and therefore contains breaking changes.
renderers
to components
react-markdown
used to let you define components for markdown constructs
(link
, delete
, break
, etc).
This proved complex as users didn’t know about those names or markdown
peculiarities (such as that there are fully formed links and link references).
See GH-549 for more
on why this changed.
See Appendix B: Components in
readme.md
for more on components.
Before (broken):
<Markdown
renderers={{
// Use a fancy hr
thematicBreak: ({node, ...props}) => <MyFancyRule {...props} />
}}
>{`***`}</Markdown>
Now (fixed):
<Markdown
components={{
// Use a fancy hr
hr: ({node, ...props}) => <MyFancyRule {...props} />
}}
>{`***`}</Markdown>
</details>
<details>
<summary>Show conversion table</summary>
| Type (renderers
) | Tag names (components
) |
| ----------------------------------- | --------------------------------------- |
| blockquote
| blockquote
|
| break
| br
|
| code
, inlineCode
| code
, pre
* |
| definition
| † |
| delete
| del
‡ |
| emphasis
| em
|
| heading
| h1
, h2
, h3
, h4
, h5
, h6
§ |
| html
, parsedHtml
, virtualHtml
| ‖ |
| image
, imageReference
| img
† |
| link
, linkReference
| a
† |
| list
| ol
, ul
¶ |
| listItem
| li
|
| paragraph
| p
|
| root
| ** |
| strong
| strong
|
| table
| table
‡ |
| tableHead
| thead
‡ |
| tableBody
| tbody
‡ |
| tableRow
| tr
‡ |
| tableCell
| td
, th
‡ |
| text
| |
| thematicBreak
| hr
|
inline
prop.
Block code is also wrapped in a pre
[text](url)
) and reference ([text][id]
) style links and
images (and their definitions) are now resolved and treated the sameremark-gfm
level
proprehype-raw
(see below), components for those elements
can also be used (for example, abbr
for
<abbr title="HyperText Markup Language">HTML</abbr>
)ordered
propReactMarkdown
in a component insteadrehypePlugins
We’ve added another plugin system: rehype. It’s similar to remark (what we’re using for markdown) but for HTML.
There are many rehype plugins.
Some examples are
@mapbox/rehype-prism
(syntax highlighting with Prism),
rehype-katex
(rendering math with KaTeX), or
rehype-autolink-headings
(adding links to headings).
See List of plugins for more plugins.
<details> <summary>Show example of feature</summary>import rehypeHighlight from 'rehype-highlight'
<Markdown rehypePlugins={[rehypeHighlight]}>{`~~~js
console.log(1)
~~~`}</Markdown>
</details>
In a lot of cases, you should not use HTML in markdown: it’s most always unsafe.
And it defeats much of the purpose of this project (not relying on
dangerouslySetInnerHTML
).
react-markdown
used to have an opt-in HTML parser with a bunch of bugs.
As we now support rehype plugins, we can defer that work to a rehype plugin.
To support HTML in markdown with react-markdown
, use
rehype-raw
.
The astPlugins
and allowDangerousHtml
(previously called escapeHtml
) props
are no longer needed and were removed.
When using rehype-raw
, you should probably use
rehype-sanitize
too.
Before (broken):
import MarkdownWithHtml from 'react-markdown/with-html'
<MarkdownWithHtml>{`# Hello, <i>world</i>!`}</MarkdownWithHtml>
Now (fixed):
import Markdown from 'react-markdown'
import rehypeRaw from 'rehype-raw'
import rehypeSanitize from 'rehype-sanitize'
<Markdown rehypePlugins={[rehypeRaw, rehypeSanitize]}>{`# Hello, <i>world</i>!`}</Markdown>
</details>
source
to children
Instead of passing a source
pass children
instead:
Before (broken):
<Markdown source="some\nmarkdown"></Markdown>
Now (fixed):
<Markdown>{`some
markdown`}</Markdown>
Or (also fixed):
<Markdown children={`some
markdown`} />
</details>
allowNode
, allowedTypes
, and disallowedTypes
Similar to the renderers
to components
change, the filtering options
also changed from being based on markdown names towards being based on HTML
names: allowNode
to allowElement
, allowedTypes
to allowedElements
, and
disallowedTypes
to disallowedElements
.
Before (broken):
<Markdown
// Skip images
disallowedTypes={['image']}
>{`![alt text](./image.url)`}</Markdown>
Now (fixed):
<Markdown
// Skip images
disallowedElements={['img']}
>{`![alt text](./image.url)`}</Markdown>
Before (broken):
<Markdown
// Skip h1
allowNode={(node) => node.type !== 'heading' || node.depth !== 1}
>{`# main heading`}</Markdown>
Now (fixed):
<Markdown
// Skip h1
allowElement={(element) => element.tagName !== 'h1'}
>{`# main heading`}</Markdown>
</details>
includeNodeIndex
to includeElementIndex
Similar to the renderers
to components
change, this option to pass more info
to components also changed from being based on markdown to being based on HTML.
Before (broken):
<Markdown
includeNodeIndex={true}
renderers={{
paragraph({node, index, parentChildCount, ...props}) => <MyFancyParagraph {...props} />
}}
>{`Some text`}</Markdown>
Now (fixed):
<Markdown
includeElementIndex={true}
components={{
p({node, index, siblingsCount, ...props}) => <MyFancyParagraph {...props} />
}}
>{`Some text`}</Markdown>
</details>
transformLinkUri
, linkTarget
The second parameter of these functions (to rewrite href
on a
or to define
target
on a
) are now hast (HTML AST)
instead of mdast (markdown AST).
transformImageUri
The second parameter of this function was always undefined
and the fourth was
the alt
(string
) on the image.
The second parameter is now that alt
.
We now use ES2015 (such as Object.assign
) and removed certain hacks to work
with React 15 and older.
FAQs
React component to render markdown
The npm package react-markdown receives a total of 2,347,239 weekly downloads. As such, react-markdown popularity was classified as popular.
We found that react-markdown demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
NIST has failed to meet its self-imposed deadline of clearing the NVD's backlog by the end of the fiscal year. Meanwhile, CVE's awaiting analysis have increased by 33% since June.
Security News
Cloudflare has launched a setup wizard allowing users to easily create and manage a security.txt file for vulnerability disclosure on their websites.
Security News
The Socket Research team breaks down a malicious npm package targeting the legitimate DOMPurify library. It uses obfuscated code to hide that it is exfiltrating browser and crypto wallet data.