Transform markdown to React with remark, an extensively tested and
pluggable parser.
Why? Using innerHTML and dangerouslySetInnerHTML in React 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.
remark-react builds a DOM in React, using React.createElement: this
means that you can display parsed & formatted Markdown content in an
application without using dangerouslySetInnerHTML
.
Installation
npm:
npm install remark-react
Table of Contents
Usage
import React from 'react'
import ReactDOM from 'react-dom'
import remark from 'remark'
import remark2react from 'remark-react'
class App extends React.Component {
constructor() {
super()
this.state = { text: '# hello world' }
this.onChange = this.onChange.bind(this)
}
onChange(e) {
this.setState({ text: e.target.value })
}
render() {
return (
<div>
<textarea value={this.state.text} onChange={this.onChange} />
<div id="preview">
{
remark()
.use(remark2react)
.processSync(this.state.text).contents
}
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'))
API
Transform markdown to React.
Options
options.createElement
How to create elements or components (Function
).
Default: require('react').createElement
options.fragment
Create fragments instead of an outer <div>
if available (Function
).
Default: require('react').Fragment
options.sanitize
Sanitation schema to use (object
or boolean
, default: undefined
).
Passed to hast-util-sanitize
.
The default schema, if none or true
is passed, adheres to GitHub’s
sanitation rules.
Setting this to false
is just as bad as using dangerouslySetInnerHTML
.
options.prefix
React key (default: h-
).
Override default elements, such as <a>
, <p>
, etc by defining an object
comprised of element: Component
key-value pairs (object
, default:
undefined
).
For example, to output <MyLink>
components instead of <a>
, and
<MyParagraph>
instead of <p>
:
remarkReactComponents: {
a: MyLink,
p: MyParagraph
}
options.toHast
Configure how to transform mdast to hast (object
, default: {}
).
Passed to mdast-util-to-hast.
Integrations
See how to integrate with other remark plugins in the Integrations section
of remark-html
.
License
MIT © Titus Wormer, modified by Tom MacWright and
Mapbox.