Compile Markdown to React with mdast
mdast-react compiles markdown to React. Built on mdast, an extensively tested and pluggable parser.
Why? Using innerHTML and dangerouslySetInnerHTML in
React.js is a common cause of XSS
attacks: user input can include script tags and other kinds of active
content that reaches across domains and harms security. mdast-react
builds a DOM in React, using React.createElement:
this means that you can display parsed & formatted Markdown content
in an application without using
npm install mdast-react
react— This plugin;
Object?) — See below.
example.js looks as follows:
var React =mdast =reactRenderer = ;var App = React;React;
All options, including the
options object itself, are optional:
— How to encode non-ASCII and HTML-escape characters: the default
generates named entities (
numbered entities (
'escape' only encodes
characters which are required by HTML to be escaped:
`, leaving non-ASCII characters untouched.
— Whether or not to allow the use of HTML inside markdown.
— Provides a way to override default elements (
by defining an object comprised of
element: Component key-value
pairs. For example, to output
<MyLink> components instead of
<MyParagraph> instead of
mdastReactComponents:a: MyLinkp: MyParagraph
These can passed to
mdast.use() as a second argument.
You can define these in
too. An example
.mdastrc file could look as follows:
Where the object at
plugins.react are the options for mdast-react.
The object at
settings determines how mdast parses markdown code.
Read more about the latter on mdast’s readme.
You still need to set
commonmark: truein mdast’s options
CommonMark support is a goal but not (yet) a
necessity. There are some (roughly 115 of 550, relating to inline
precedence, lists, emphasis and strongness) issues which I’d like
to cover in the future. Note that this sounds like a lot, but they
have to do with obscure differences which do not often occur in the
real world. Read more on some of the reasoning in
mdast-react works great with:
mdast-toc, which generates tables of contents;
mdast-github, which generates references to GitHub issues, PRs, users, and more;
All mdast nodes
can be compiled to HTML. In addition, mdast-react looks for an
attributes object on each node it compiles and adds the found properties
as HTML attributes on the compiled tag.