custom syntax using react-markdown

218 views Asked by At

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;

1

There are 1 answers

0
Rose On
import React from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";

const CustomMarkdown = ({ children }) => {
  const renderers = {
    text: (text) => {
      const regex = /{{(.*?)}}/g;
      const parts = text?.children[0].split(regex);
      return parts.map((part, i) =>
        i % 2 === 1 ? (
          <span key={i} style={{ color: "blue" }}>
            {part}
          </span>
        ) : (
          part
        )
      );
    },
    h2: (text) => {
      const regex = /{{(.*?)}}/g;
      const parts = text?.children[0].split(regex);
      return parts.map((part, i) =>
        i % 2 === 1 ? (
          <span key={i} style={{ color: "blue" }}>
            {part}
          </span>
        ) : (
          <h2 key={i}>{part}</h2>
        )
      );
    },
    p: (text) => {
      const regex = /{{(.*?)}}/g;
      const parts = text?.children[0].split(regex);
      return parts.map((part, i) =>
        i % 2 === 1 ? (
          <span key={i} style={{ color: "blue" }}>
            {part}
          </span>
        ) : (
          <p key={i}>{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:

    <CustomMarkdown>
      ## Header {{Some text in blue}} and other text
    </CustomMarkdown>