Sometimes, we want to use the marked Markdown library in our React app.
In this article, we’ll look at how to use the marked Markdown library in our React app.
Use the marked Markdown Display Component in React
To use the marked Markdown display component in our React app, we just call, the marked
function that comes with the marked library to convert the Markdown string into an HTML string.
Then we can render the HTML string with dangerouslySetInnerHTML
.
For instance, we can write:
import React from "react";
import marked from "marked";
export default function App() {
const getMarkdownText = () => {
const rawMarkup = marked("This is _Markdown_.", { sanitize: true });
return { __html: rawMarkup };
};
return <div dangerouslySetInnerHTML={getMarkdownText()} />;
}
We create the getMarkdownText
function to convert the “This is _Markdown_.”
Markdown string into an HTML string with the marked
function.
And we set sanitize
to true
to escape any special characters.
Then we set the dangerouslySetInnerHTML
prop of the div to the HTML string returned by the getMarkdownText
function.
Conclusion
To use the marked Markdown display component in our React app, we just call, the marked
function that comes with the marked library to convert the Markdown string into an HTML string.
Then we can render the HTML string with dangerouslySetInnerHTML
.