I need to add my own syntax to react-markdown, for example so that the text inside {{ }} changes color to blue and at the same time works correctly using another syntax, for example ## Header {{ }}
import React from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
const CustomMarkdown = ({ children }) => {
console.log(children);
const renderers = {
h2: (text) => {
const regex = /{{(.*?)}}/g;
const parts = text?.children[0].split(regex);
return parts.map((part, i) =>
i % 2 === 1 ? (
<span style={{ color: "blue" }}>{part}</span>
) : (
<h2>{part}</h2>
)
);
},
p: (text) => {
const regex = /{{(.*?)}}/g;
const parts = text?.children[0].split(regex);
return parts.map((part, i) =>
i % 2 === 1 ? (
<span style={{ color: "blue" }}>{part}</span>
) : (
<p
// style={{ display: "inline" }}
>
{part}
</p>
)
);
},
};
return (
<ReactMarkdown remarkPlugins={[remarkGfm]} components={renderers}>
{children}
</ReactMarkdown>
);
};
export default CustomMarkdown;
This uses the text renderer to apply a custom color to the text inside the {{ }}. Each dynamically created element needs to have a key attribute added to ensure efficient updating and re-rendering of React components.
Now any text inside {{ }} will be styled blue. For example: