How to use react-markdown to create custom React components
Are you using a CMS which provides data to the React/Next frontend ?
Did you ever want to create custom components and render them in a custom way in React but had no idea how to do it?
If both answers are yes keep reading.
I will show you very fast how to create your own custom components using react-markdown which also supports html rendering.
Our custom “product” component
Let us assume that your CMS returns for the post content the following result string
1 2 |
<h1>Below you can find our best product</h1> <product price="50" year="2024">My product description</product> |
You notice that I am using the product html element which does not exist by default.
We will handle and render it accordingly with the react-markdown library.
The react-markdown library can handle both html with rehype and markdown so do not get confused, we can use markdown but are not forced. I am using html here.
Install in your react application
1 |
yarn add react-markdown rehype-raw |
Your Post.tsx file will look like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import React from 'react'; import ReactMarkdown from 'react-markdown'; import rehypeRaw from 'rehype-raw'; interface Props { content: string; } const Post: React.FC<Props> = ({ content }) => { return ( <ReactMarkdown rehypePlugins={[rehypeRaw]} components={{ // @ts-ignore product: (product) => { return ( <div> Price: {product.price} Year: {product.year} Description: {product.children[0]} </div> ); }, }} > {content} </ReactMarkdown> ); }; export default Post; |
Then you will see in the frontend the custom element you return for the custom product html tag!
That is all, now you can create your custom components from the cms and render them according to your wishes in React.
Enjoy!