Using Marked In React

- 1 answer

I want to use marked in reactjs as described in the reactjs docs.


I use babel so I import marked like this:

import { marked } from 'marked';

Unfortunately the import statement does not work. marked is not defined. How do I have to import marked here, so that I can use it?



Here's one way to use marked with React:

  1. Ensure that you've installed marked
  2. Include marked in your project's package.json file:
// package.json
  dependencies: {
    react: "^17.0.0",
    marked: "^4.0.0",
  1. Import marked in your .jsx(or related) file:
import { marked } from "marked";
  1. Use the dangerouslySetInnerHTML approach as shown in the example below:
import React from "react";
import { marked } from "marked";

class MarkdownExample extends React.Component {
  getMarkdownText() {
    var rawMarkup = marked.parse("This is _Markdown_.");
    return { __html: rawMarkup };
  render() {
    return <div dangerouslySetInnerHTML={this.getMarkdownText()} />;

The dangerouslySetInnerHTML attribute gives you the ability to work with raw (HTML) markup. Make sure to take care when using this attribute, though!

Alternative (Safe)

If you don't want to use dangerouslySetInnerHTML and safely render HTML. Try marked-react, which internally uses marked to render the html elements as react components

npm i marked-react
import Markdown from "marked-react";

const MarkdownComponent = () => {
  return <Markdown>{rawmarkdown}</Markdown>;

Another alternative is react-markdown