React-Markdown

React-Markdown

React Markdown

React Markdown lets you takes your existing MD files (think ReadMe files) and easily turn them into elegant web content using a framework of your choice and 3rd party plugins.

1Dislaimer: This site is built using React-Markdown

React component to render markdown.

Feature highlights

  • [x] safe by default (no dangerouslySetInnerHTML or XSS attacks)
  • [x] components (pass your own component to use instead of <h2> for ## hi)
  • [x] plugins (many plugins you can pick and choose from)
  • [x] compliant (100% to CommonMark, 100% to GFM with a plugin)

Contents

What is this?

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.

When should I use this?

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:

1npm install react-markdown
2

A basic hello world:

1import React from 'react';
2import ReactMarkdown from 'react-markdown';
3import ReactDom from 'react-dom';
4
5ReactDom.render(<ReactMarkdown></ReactMarkdown>, document.body);
6
1<h1>
2  Hello, <em>world</em>!
3</h1>
4

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):

1import React from 'react';
2import ReactDom from 'react-dom';
3import ReactMarkdown from 'react-markdown';
4import remarkGfm from 'remark-gfm';
5
6const markdown = `Just a link: https://reactjs.com.`;
7
8ReactDom.render(
9  <ReactMarkdown children={markdown} remarkPlugins={[remarkGfm]} />,
10  document.body
11);
12

Show equivalent JSX

1<p>
2  Just a link: <a href="https://reactjs.com">https://reactjs.com</a>.
3</p>
4

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).

See the source code here.

Examples

Use a plugin

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 ReactMarkdown from 'react-markdown';
3import ReactDom from 'react-dom';
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
20ReactDom.render(
21  <ReactMarkdown children={markdown} remarkPlugins={[remarkGfm]} />,
22  document.body
23);
24

Show equivalent JSX

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>
12    <li>Lists</li>
13    <li>
14      <input checked={false} readOnly={true} type="checkbox" /> todo
15    </li>
16    <li>
17      <input checked={true} readOnly={true} type="checkbox" /> done
18    </li>
19  </ul>
20  <p>A table:</p>
21  <table>
22    <thead>
23      <tr>
24        <td>a</td>
25        <td>b</td>
26      </tr>
27    </thead>
28  </table>
29</>
30

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.

1remark-gfm
has an option to allow only double tildes for strikethrough:

1import React from 'react';
2import ReactMarkdown from 'react-markdown';
3import ReactDom from 'react-dom';
4import remarkGfm from 'remark-gfm';
5
6ReactDom.render(
7  <ReactMarkdown remarkPlugins={[[remarkGfm, { singleTilde: false }]]}>
8    This ~is not~ strikethrough, but ~~this is~~!
9  </ReactMarkdown>,
10  document.body
11);
12

Show equivalent JSX

1<p>
2  This ~is not~ strikethrough, but <del>this is</del>!
3</p>
4

<

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:

1import React from 'react';
2import ReactDom from 'react-dom';
3import ReactMarkdown 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
15ReactDom.render(
16  <ReactMarkdown
17    children={markdown}
18    components={{
19      code({ node, inline, className, children, ...props }) {
20        const match = /language-(\w+)/.exec(className || '');
21        return !inline && match ? (
22          <SyntaxHighlighter
23            children={String(children).replace(/\n$/, '')}
24            style={dark}
25            language={match[1]}
26            PreTag="div"
27            {...props}
28          />
29        ) : (
30          <code className={className} {...props}>
31            {children}
32          </code>
33        );
34      },
35    }}
36  />,
37  document.body
38);
39

Show equivalent JSX

1<>
2  <p>Here is some JavaScript code:</p>
3  <pre>
4    <SyntaxHighlighter
5      language="js"
6      style={dark}
7      PreTag="div"
8      children="console.log('It works!')"
9    />
10  </pre>
11</>
12

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.

1import React from 'react';
2import ReactDom from 'react-dom';
3import ReactMarkdown from 'react-markdown';
4import remarkMath from 'remark-math';
5import rehypeKatex from 'rehype-katex';
6
7import 'katex/dist/katex.min.css'; // `rehype-katex` does not import the CSS for you
8
9ReactDom.render(
10  <ReactMarkdown
11    children={`The lift coefficient ($C_L$) is a dimensionless coefficient.`}
12    remarkPlugins={[remarkMath]}
13    rehypePlugins={[rehypeKatex]}
14  />,
15  document.body
16);
17

Show equivalent JSX

1<p>
2  The lift coefficient (
3  <span className="math math-inline">
4    <span className="katex">
5      <span className="katex-mathml">
6        <math xmlns="http://www.w3.org/1998/Math/MathML">{/* … */}</math>
7      </span>
8      <span className="katex-html" aria-hidden="true">
9        {/* … */}
10      </span>
11    </span>
12  </span>
13  ) is a dimensionless coefficient.
14</p>
15

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:

Syntax

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.

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 use rehype-raw:

1import React from 'react';
2import ReactDom from 'react-dom';
3import ReactMarkdown from 'react-markdown';
4import rehypeRaw from 'rehype-raw';
5
6const input = `<div class="note">
7
8Some *emphasis* and <strong>strong</strong>!
9
10</div>`;
11
12ReactDom.render(
13  <ReactMarkdown rehypePlugins={[rehypeRaw]} children={input} />,
14  document.body
15);
16

Show equivalent JSX

1<div class="note">
2  <p>
3    Some <em>emphasis</em> and <strong>strong</strong>!
4  </p>
5</div>
6

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!

Appendix B: Components

You can also change the things that come from markdown:

1<ReactMarkdown
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: ({ node, ...props }) => <i style={{ color: 'red' }} {...props} />,
7  }}
8/>
9

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 (and title), etc. There are some extra props passed.

  • code
    • inline (boolean?) — set to true for inline code
    • className (string?) — set to language-js or so when using js
  • h1, h2, h3, h4, h5, h6
    • level (number between 1 and 6) — heading rank
  • input (when using remark-gfm)
    • checked (boolean) — whether the item is checked
    • disabled (true)
    • type ('checkbox')
  • li
    • index (number) — number of preceding items (so first gets 0, etc.)
    • ordered (boolean) — whether the parent is an ol or not
    • checked (boolean?) — null normally, boolean when using remark-gfm’s tasklists
    • className (string?) — set to task-list-item when using remark-gfm and the item1 is a tasklist
  • ol, ul
    • depth (number) — number of ancestral lists (so first gets 0, etc.)
    • ordered (boolean) — whether it’s an ol or not
    • className (string?) — set to contains-task-list when using remark-gfm and the list contains one or more tasklists
  • td, th (when using remark-gfm)
    • style (Object?) — something like {textAlign: 'left'} depending on how the cell is aligned
    • isHeader (boolean) — whether it’s a th or not
  • tr (when using remark-gfm)
    • isHeader (boolean) — whether it’s in the thead or not

Every 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 option
  • sourcePosition (Object) — see rawSourcePos option
  • index and siblingCount (number) — see includeElementIndex option
  • target on a (string) — see linkTarget option

Security

Use of React-Markdown is secure by default. Overwriting transformLinkUri or transformImageUri 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.

Related

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.

License

MIT © Espen Hovlandsdal