Unlock the Power of Markdown in Your React Apps
Markdown has been a staple in the developer community since 2004, allowing us to create content for various platforms with ease. But did you know that rendering Markdown safely in a React component can be a challenge? That’s where react-markdown comes in – a powerful library that converts Markdown text into HTML code, ensuring your app remains secure.
What is react-markdown?
react-markdown is a React component built on top of remark, a Markdown preprocessor. It uses a syntax tree to build the virtual DOM, eliminating the need for the dangerouslySetInnerHTML prop, which can leave your app vulnerable to cross-site scripting (XSS) attacks.
Installing react-markdown
Getting started with react-markdown is a breeze. Simply run the following command in your terminal:
npm install react-markdown
Or, if you prefer yarn:
yarn add react-markdown
Using react-markdown: A Simple Example
To use react-markdown, simply wrap your Markdown text in the component:
import ReactMarkdown from 'eact-markdown';
const markdown = `React-Markdown is Awesome.`;
const App = () => {
return <ReactMarkdown>{markdown}</ReactMarkdown>;
};
The rendered output will be “React-Markdown is Awesome.”
Supported Markdown Syntax
react-markdown supports a range of Markdown syntax out of the box, including:
- Headers
- Bold and italic text
- Lists
- Links
- Images
- Code blocks
Taking it to the Next Level with Plugins
While react-markdown provides a solid foundation, you can enhance its functionality with plugins. remark, the parent project of react-markdown, offers a range of plugins, including remark-gfm, which adds support for GitHub Flavored Markdown.
To use plugins, simply pass them to the remarkPlugins or rehypePlugins prop:
import ReactMarkdown from 'eact-markdown';
import remarkGfm from 'emark-gfm';
const markdown = `~~Strikethrough~~`;
const App = () => {
return (
<ReactMarkdown remarkPlugins={[remarkGfm]}>
{markdown}
</ReactMarkdown>
);
};
Special Syntax for remark-gfm
The remark-gfm plugin unlocks a range of special functionalities, including:
- Tables
- Strikethrough text
- To-do lists
Check out the live demo below:
See the Pen React-Markdown Table using Remark-gfm by Akash Mittal (@akash-mittal) on CodePen.