Skip to content
Advertisement

How do I render Markdown from a React component?

I have my documentation written in markdown and I would like to render those files from my JSX (ES6+CommonJS) code into React components. How can I achieve this?

For example I have styles.markdown and I would like to render it into a <p> tag.

Advertisement

Answer

You can use React-Markdown:

const React = require('react')
const ReactDOM = require('react-dom')
const ReactMarkdown = require('react-markdown')

const input = '# This is a headernnAnd this is a paragraph'

ReactDOM.render(<ReactMarkdown source={input} />, document.getElementById('container'))

Or… You can just create a simple React component that wraps a call to a Markdown parser. There are two very good ones for JavaScript:

Now, you can create a component like this:

var MarkdownViewer = React.createClass({
    render: function() {
        // pseudo code here, depends on the parser
        var markdown = markdown.parse(this.props.markdown);
        return <div dangerouslySetInnerHTML={{__html:markdown}} />;
    }
});

There used to have one already, but it doesn’t seem to be maintained anymore: https://github.com/tcoopman/markdown-react

Also, if you need a React Markdown Editor, check out: react-mde. Disclaimer: I am the author.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement