Research
Security News
Threat Actor Exposes Playbook for Exploiting npm to Build Blockchain-Powered Botnets
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
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.
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 plugins={[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 nameallowDangerousHtml
(boolean
, default: false
)allowDangerousHtml: true
to allow dangerous html instead.
See securityskipHtml
(boolean
, default: false
)sourcePos
(boolean
, default: false
)data-sourcepos="3:1-3:13"
)rawSourcePos
(boolean
, default: false
)sourcePosition: {start: {line: 3, column: 1}, end:…}
)includeNodeIndex
(boolean
, default: false
)index
and parentChildCount
in props to all renderersallowedTypes
(Array.<string>
, default: list of all types)disallowedTypes
).
All types are available at ReactMarkdown.types
disallowedTypes
(Array.<string>
, default: []
)allowedTypes
)allowNode
((node, index, parent) => boolean?
, optional)allowedTypes
/ disallowedTypes
is used first!unwrapDisallowed
(boolean
, default: false
)strong
is not allowed, it and it’s content is dropped,
but with unwrapDisallowed
the node itself is dropped but the content usedlinkTarget
(string
or (url, text, title) => string
, optional)_blank
for <a target="_blank"…
)transformLinkUri
((uri) => 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
((uri) => string
, default:
./uri-transformer.js
, optional)transformLinkUri
but for imagesrenderers
(Object.<Component>
, default: {}
)ReactMarkdown.renderers
).
Which props are passed varies based on the nodeplugins
(Array.<Plugin>
, default: []
)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)
<>
<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 plugins={[[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 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)
<>
<p>Here is some JavaScript code:</p>
<SyntaxHighlighter language="js" style={dark} children="console.log('It works!')" />
</>
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 react-katex
:
import React from 'react'
import ReactMarkdown from 'react-markdown'
import {InlineMath, BlockMath} from '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}) => <InlineMath math={value} />,
math: ({value}) => <BlockMath math={value} />
}
render(
<ReactMarkdown
plugins={[math]}
renderers={renderers}
children={`The lift coefficient ($C_L$) is a dimensionless coefficient.`}
/>,
document.body
)
<p>
The lift coefficient (<InlineMath math="C_L" />) 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), 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)
<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 parseHtml = htmlParser({
isValidNode: (node) => node.type !== 'script',
processingInstructions: [
/* ... */
]
})
<ReactMarkdown astPlugins={[parseHtml]} allowDangerousHtml children={markdown} />
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
— If allowDangerousHtml
is not on and skipHtml
is off, a
naive HTML parser is used to support basic HTMLparsedHtml
— If allowDangerousHtml
is on, skipHtml
is off, and
html-parser
is used, more advanced HTML is supportedWith 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>
)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.
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.
FAQs
React component to render markdown
The npm package react-markdown receives a total of 1,789,446 weekly downloads. As such, react-markdown popularity was classified as popular.
We found that react-markdown demonstrated a not healthy version release cadence and project activity because the last version was released 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.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.
Security News
NVD’s backlog surpasses 20,000 CVEs as analysis slows and NIST announces new system updates to address ongoing delays.
Security News
Research
A malicious npm package disguised as a WhatsApp client is exploiting authentication flows with a remote kill switch to exfiltrate data and destroy files.