Using marked in react

If you just want to import marked:

import marked from 'marked';

Then call the function in your component:

marked('# Markdown');

Here is another way of using marked with React Hooks:

  1. Create your MarkedConverter component
import { useState } from 'react'
import marked from 'marked'

export const MarkedConverter = () => {
  const [markedVal, setMarkedVal] = useState(
    '# Welcome to my React Markdown Previewer!'
  )
  return <div dangerouslySetInnerHTML={createMarkUp(markedVal)}></div>
}
  1. Create Markup function and pass the value from MarkedConverter Component
export const createMarkUp = (val) => {
 return { __html: marked(val) }
}
  1. Finally you can import MarkedConverter Component to any of your Component

With the marked-wrapper react-marked-markdown:

import { MarkdownPreview } from 'react-marked-markdown'

export default ({ post }) => (
  <div>
    <h1>{ post.title }</h1>
    <MarkdownPreview value={ post.content }/>
  </div>
)

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


Tags:

Reactjs