Kristi Jorgji

How to use react-markdown to create custom React components

Kristi Jorgji1 min readComments

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

<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

yarn add react-markdown rehype-raw

Your Post.tsx file will look like:

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!

CategoriesReact
Tagshtml

Written by Kristi Jorgji

Software engineer writing about programming, architecture, and the books that shape how I build products.

Share

Related posts

Comments

Comments are powered by Disqus, a third-party service.Privacy policy