DEV Community

Mingming Ma
Mingming Ma

Posted on

A trick to know inline-code in react-markdown

If you are using react-markdown lasted version, you may find that inline property is removed.

I have faced same situation as I need to deal with different markdown rendering for the inline code and Fenced Code Blocks to solved this issue.

Take a look at the example code shows Syntax Highlighting to code blocks from this blog post, which has used inline property before it is removed:


    <Markdown
      remarkPlugins={[remarkGfm]}
      rehypePlugins={[rehypeRaw]}
      components={{
        code({ node, inline, className, children, ...props }: any) {
          const match = /language-(\w+)/.exec(className || '');

          return !inline && match ? (
            <SyntaxHighlighter style={dracula} PreTag="div" language={match[1]} {...props}>
              {String(children).replace(/\n$/, '')}
            </SyntaxHighlighter>
          ) : (
            <code className={className} {...props}>
              {children}
            </code>
          );
        },
      }}
    >
      {markdown}
    </Markdown>
Enter fullscreen mode Exit fullscreen mode

Since now we don't have inline property in react-markdown, you may say we can still use the match logic to detect. While it is good at most time when you specify the language next to the backticks. Without specifying the language, then the match

const match = /language-(\w+)/.exec(className || '');
Enter fullscreen mode Exit fullscreen mode

is same for inline code and code blocks, because className is undefined in both situation.

So here is how I resolved this puzzle, I found when you give code block syntax to react-markdown, the String(children) always has the new line '\n' no matter language is given or not. For the inline code syntax, String(children) does not has the new line '\n', which also aligns with its literal meaning. So here is this trick:

        code({ className, children, ...props }: any) {
          const match = /language-(\w+)/.exec(className || '');

          return String(children).includes("\n") || match ? (
            <SyntaxHighlighter> ... </SyntaxHighlighter>
          ) : (
            <code> ... </code>
          );
Enter fullscreen mode Exit fullscreen mode

Fun fact: I got to know the inline property "solution" when I asked chatgpt how to distinguish inline code and code block, and googled out the above mentioned post from that.

That's it. Hope it helps. See you next time.

Top comments (0)