I want to use marked in reactjs as described in the reactjs docs.
<div>{marked(mystring)}</div>
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?
This is because when you use an arrow function, the event handler is automatically bound to the component instance so you don't need to bind it in the constructor. When you use an arrow function you are binding this lexically.
markdown-to-jsx is an easy-to-use markdown component that takes Github-flavored Markdown (GFM) and makes native JSX without dangerous hacks.
Here's one way to use marked
with React
:
marked
marked
in your project's package.json
file:// package.json
{
dependencies: {
react: "^17.0.0",
marked: "^4.0.0",
},
}
marked
in your .jsx
(or related) file:import { marked } from "marked";
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!
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
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:
- 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>
}
- Create Markup function and pass the value from MarkedConverter Component
export const createMarkUp = (val) => {
return { __html: marked(val) }
}
- Finally you can import MarkedConverter Component to any of your Component
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With