Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 922
Capuchin Avatar asked Aug 07 '15 10:08

Capuchin


People also ask

What is render markdown?

renderMarkdown transforms the markdown text provided by the user in either the file or text variable. The transformation is either written to the output file or returned to the user. The default rendering target is "HTML".

What is markdown to JSX?

markdown-to-jsx is an easy-to-use markdown component that takes Github-flavored Markdown (GFM) and makes native JSX without dangerous hacks.

How do you render a markdown in HTML?

The first step to convert Markdown to HTML is to open your Markdown document in Atom. Then toggle the Markdown preview by pressing the CTRL+SHIFT+M keyboard shortcut. Another way to toggle the Markdown preview is from Packages —> Markdown Preview —> Toggle Preview.


2 Answers

You can use React-Markdown:

const React = require('react') const ReactDOM = require('react-dom') const ReactMarkdown = require('react-markdown')  const input = '# This is a header\n\nAnd 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:

  • Remarkable
  • Marked

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.

like image 121
André Pena Avatar answered Sep 21 '22 19:09

André Pena


The package react-markdown with Markdown component will be good choice:

import React from 'react' import Markdown from 'react-markdown'      var src = "# This is markdown document"      React.render(   <Markdown children={src} />,   document.getElementById('root') ) 

You can write inplace here-docs like this:

<Markdown>   # Header    * dotted lists   * [url](/doc) </Markdown> 

It is possible to specify transformers for link-urls and image-urls and much more.

like image 39
oklas Avatar answered Sep 19 '22 19:09

oklas