React Markdown



Markdown component for React using remark.

Learn markdown here and check out the demo here.

Install

Markdown

npm:

Why this one?

There are other ways for markdown in React out there so why use this one?The two main reasons are that they often rely on dangerouslySetInnerHTML orhave bugs with how they handle markdown.react-markdown uses a syntax tree to build the virtual dom which allows forupdating only the changing DOM instead of completely overwriting.react-markdown is 100% CommonMark (optionally GFM) compliant and hasextensions to support custom syntax.

Use

  • Markdown-to-jsx provides very efficeint functionality to interact with markdown in React component. It allows replacing/overriding of any HTML element with your Custom Component for markdown, here is the doc.
  • 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 (optionally GFM) compliant and has extensions to support custom syntax.

A basic hello world:

Show equivalent JSX

Here is an example using requires, passing the markdown as a string, and howto use a plugin (remark-gfm, which adds support for strikethrough,tables, tasklists and URLs directly):

Jun 17, 2020 We will run the following command to create a simplest ReactJS named react-markdown-viewer. React-markdown-viewer is just my app’s nam e, and this will create a new folder and configuration based.

Show equivalent JSX

API

props

  • children (string, default: ')
    Markdown to parse
  • className (string?)
    Wrap the markdown in a div with this class name
  • allowDangerousHtml (boolean, default: false)
    This project is safe by default and escapes HTML.Use allowDangerousHtml: true to allow dangerous html instead.See security
  • skipHtml (boolean, default: false)
    Ignore HTML in Markdown
  • sourcePos (boolean, default: false)
    Pass a prop to all renderers with a serialized position(data-sourcepos='3:1-3:13')
  • rawSourcePos (boolean, default: false)
    Pass a prop to all renderers with their position(sourcePosition: {start: {line: 3, column: 1}, end:…})
  • includeNodeIndex (boolean, default: false)
    Pass index and parentChildCount in props to all renderers
  • allowedTypes (Array.<string>, default: list of all types)
    Node types to allow (can’t combine w/ disallowedTypes).All types are available at ReactMarkdown.types
  • disallowedTypes (Array.<string>, default: [])
    Node types to disallow (can’t combine w/ allowedTypes)
  • allowNode ((node, index, parent) => boolean?, optional)
    Function called to check if a node is allowed (when truthy) or not.allowedTypes / disallowedTypes is used first!
  • unwrapDisallowed (boolean, default: false)
    Extract (unwrap) the children of not allowed nodes.By default, when strong is not allowed, it and it’s content is dropped,but with unwrapDisallowed the node itself is dropped but the content used
  • linkTarget (string or (url, text, title) => string, optional)
    Target to use on links (such as _blank for <a target='_blank'…)
  • transformLinkUri ((uri) => string, default:./uri-transformer.js, optional)
    URL to use for links.The default allows only http, https, mailto, and tel, and isavailable at ReactMarkdown.uriTransformer.Pass null to allow all URLs.See security
  • transformImageUri ((uri) => string, default:./uri-transformer.js, optional)
    Same as transformLinkUri but for images
  • renderers (Object.<Component>, default: {})
    Object mapping node types to React components.Merged with the default renderers (available at ReactMarkdown.renderers).Which props are passed varies based on the node
  • plugins (Array.<Plugin>, default: [])
    List of remark plugins to use.See the next section for examples on how to pass options

Examples

Use a plugin

This example shows how to use a plugin.In this case, remark-gfm, which adds support forstrikethrough, tables, tasklists and URLs directly:

Show equivalent JSX

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 optionssecond.remark-gfm has an option to allow only double tildes for strikethrough:

Show equivalent JSX

Use custom renderers (syntax highlight)

This example shows how you can overwrite the normal handling of a node bypassing a renderer.In this case, we apply syntax highlighting with the seriously super amazingreact-syntax-highlighter by@conorhastings:

React markdown viewer
Show equivalent JSX

Use a plugin and custom renderers (math)

This example shows how a syntax extension is used to support math in markdownthat adds new node types (remark-math), which are then handled byrenderers to use @matejmazur/react-katex:

Show equivalent JSX

Appendix A: HTML in markdown

Try Something Like This: Import Fs From 'fs'; Import React, { Component, PropTypes } From 'react'; Class Markdown Extends Component { Construc...

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), you canreact-markdown/with-html:

Show equivalent JSX

If you want to specify options for the HTML parsing step, you can instead importthe extension directly:

Appendix B: Node types

The node types available by default are:

  • root — Whole document
  • text — Text (foo)
  • break — Hard break (<br>)
  • paragraph — Paragraph (<p>)
  • emphasis — Emphasis (<em>)
  • strong — Strong (<strong>)
  • thematicBreak — Horizontal rule (<hr>)
  • blockquote — Block quote (<blockquote>)
  • link — Link (<a>)
  • image — Image (<img>)
  • linkReference — Link through a reference (<a>)
  • imageReference — Image through a reference (<img>)
  • list — List (<ul> or <ol>)
  • listItem — List item (<li>)
  • definition — Definition for a reference (not rendered)
  • heading — Heading (<h1> through <h6>)
  • inlineCode — Inline code (<code>)
  • code — Block of code (<pre><code>)
  • html — HTML node (Best-effort rendering)
  • virtualHtml — If allowDangerousHtml is not on and skipHtml is off, anaive HTML parser is used to support basic HTML
  • parsedHtml — If allowDangerousHtml is on, skipHtml is off, andhtml-parser is used, more advanced HTML is supported

With remark-gfm, the following are also available:

  • delete — Delete text (<del>)
  • table — Table (<table>)
  • tableHead — Table head (<thead>)
  • tableBody — Table body (<tbody>)
  • tableRow — Table row (<tr>)
  • tableCell — Table cell (<td> or <th>)

Security

Use of react-markdown is secure by default.Overwriting transformLinkUri or transformImageUri to something insecure orturning allowDangerousHtml on, will open you up to XSS vectors.Furthermore, the plugins you use and renderers you write may be insecure.

Related

  • MDX— JSX in markdown
  • remark-gfm— Plugin for GitHub flavored markdown support

Contribute

See contributing.md in remarkjs/.github for waysto 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 toabide by its terms.

License

MIT © Espen Hovlandsdal

August 27th, 2016

In this article I will tell you about how to create Markdown Editor with React.js and Web Storage

Purpose of this article is not to teach you React.js from scratch, I’m only just going to show you how to create a specific project using React.js and explain the code

If you want to know more about React.js and explore this technology, I recommend that you go through the following courses on Codecademy

In this project, we will use the following libraries and technologies: React.js, Babel, jQuery, Bootstap, Web Storage, Marked.js and Highlight.js

1) React.js — JavaScript Library for Building User Interfaces

2) Babel — Babel is a JavaScript compiler. We will use it for Setting up React for ES6

3) Marked.js — A markdown parser and compiler

4) Highlight.js — Syntax highlighting for the Web

5 Min Quickstart

Get started by creating a new folder for your project, and name it anything you like. Then, inside that folder, create additional folders and files to match the following structure

Start by creating a index.html file with the connected necessary libraries

Open the js/index.babel in your favorite code editor (for example Sublime Text 3 or Atom) and create a new component that simply displays Hello World on page

Now, run your website on a web server. If you see Hello World on page, it means that you have done everything correctly

If you do not have installed MAMP or WAMP server, for this project you can use Node.js local-web-server package

Now we can get started

First we need to create a text box and markdown preview box where you can see the result of the work

To do this, replace the render function in your component with

and add the following styles to your css/style.css file

Now when you run, your page will look like this

The next step we define a initial default value that the user will see in a textarea. To do this, add getInitialState function before render

and replace

with

Now, every time you run the page, you’ll see the following text in a textarea

But you’ve probably noticed that in the preview block nothing. Let’s fix it. Add rawMarkup function immediately after getInitialState that will parse the contents of the text box and output the result in preview box

and replace

with

In this code snippet, I use the standard recommended settings specified in the project repository Marked.js here https://github.com/chjj/marked#usage

and added support syntax highlighting using highlight.js library

and the following code snippet

takes a this.state.content as input, in this case, the contents of the textarea as a result of the output we get the HTML that you will see in preview box

If you try to change the contents of the textarea notice that your changes are not displayed in the preview box. To fix this, add the following handleChange function after getInitialState

and replace

with

Function handleChange is attached to the textarea onChange event. The handleChange function updates the components state with the new value of textarea. This causes the component to re-render with the new value

So when you change the markdown in the textarea field you will see changes in the preview

At this point, your code in index.babel file should look like this

index.babel

Using Web Storage

Suppose a user has written a large amount of text and reload the page by accident, reset computer or even any of the case for which the user did not have time or are not able to save the typed text. The user will probably be upset

What can we do in this case and how to prevent it?

Not

We will keep all written user’s markdown to Local Storage and after each restart page, restarted browser or rebooting the PC, the user will see the text written by him

To do this, add the componentWillMount function immediately after rawMarkup

This code snippet we use to load JavaScript, which is in the file ./js/storage.js on our page within the script tag and execute it every time our component is rendered

Note that the path to storage.js file must be specified relative to the file index.html

Now include the jQuery adding to render

and add the following code in your js/storage.js file

or without jQuery

In this code snippet, we check the user’s browser supports Local Storage (you can check the browser compatibility using the service Can I Use) and if Local Storage is support we add an event listener to the textarea. Every time the input event is fired on them, it means something has changed and we save textarea contents with all changes to Local Storage with markdownStorage key

Finally, replace the initial default value

with add text from Local Storage

Now, if the user has in Local Storage markdownStorage key, to the textarea will be inserted its contents. If markdownStorage key not found or empty then user will see a default value

Full Code

index.html

The Best React Markdown Package

css/style.css

React Markdown Custom Renderer

js/index.babel

React Markdown Mdx

js/storage.js





Comments are closed.