Markdown rendering error when typing: ``Hello

27 Views Asked by At

I am using react markdown library. Here is my code:

import Markdown from 'react-markdown';
import PreClass from './PreClass';

type MarkdownFormatTextProps = {
    markdown: string;
    tagName?: string;
};

const MarkdownFormatText = ({ markdown, tagName }: MarkdownFormatTextProps) => {
    return (
        <article className=" prose prose-pre:w-[600px] prose-sm prose-ul:leading-[6px] prose-code:text-[15px] prose-blockquote:leading-[6px] prose-ol:leading-[6px] prose-p:leading-[20px] prose-li:relative prose-li:bottom-[-5px]">
            {tagName && (
                <span style={{ color: '#3297ff' }} className="cursor-pointer">
                    {tagName}
                </span>
            )}
            <Markdown unwrapDisallowed children={markdown} skipHtml components={{ pre: PreClass }} />
        </article>
    );
};

export default MarkdownFormatText;

When I type in: ```hello

Then an error will be displayed.

enter image description here

1

There are 1 best solutions below

0
Mr. Polywhirl On

Did you read the docs?

https://github.com/remarkjs/react-markdown?tab=readme-ov-file#use-custom-components-syntax-highlight

You need to add the import:

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'

And use it in your component:

import React from 'react'
import { createRoot } from 'react-dom/client'
import Markdown from 'react-markdown'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { dark } from 'react-syntax-highlighter/dist/esm/styles/prism'

// Did you know you can use tildes instead of backticks for code in markdown? ✨
const markdown = `Here is some JavaScript code:

~~~js
console.log('It works!')
~~~
`

createRoot(document.body).render(
  <Markdown
    children={markdown}
    components={{
      code(props) {
        const {children, className, node, ...rest} = props
        const match = /language-(\w+)/.exec(className || '')
        return match ? (
          <SyntaxHighlighter
            {...rest}
            PreTag="div"
            children={String(children).replace(/\n$/, '')}
            language={match[1]}
            style={dark}
          />
        ) : (
          <code {...rest} className={className}>
            {children}
          </code>
        )
      }
    }}
  />
)