3

I am using the react-markdown (https://www.npmjs.com/package/react-markdown) component to render markdown. I ran into an issue with rendering `. It seems like it is not applying the highlighting aspect.

This is what I am trying to allow.

Some text with a hightlight foo bar

enter image description here

  const components = {
    code({ inline, className, children, ...props }: any) {
      const match = /language-(\w+)/.exec(className ?? '');
      return !inline && match ? (
        <SyntaxHighlighter
          language={match[1]}
          PreTag="div"
          children={String(children).replace(/\n$/, '')}
          {...props}
        />
      ) : (
        <code className={className} {...props} />
      );
    },
  };

  return (
    <ReactMarkdown components={components} remarkPlugins={[gfm]}>
      {content}
    </ReactMarkdown>
  );

Foo bar doesn't show up using react-markdown. Anyone have any suggestions?

enter image description here

Thanks!

xjinx
  • 185
  • 8

1 Answers1

0

I ran into this problem and fixed it with a bit of css.

Separate the inline condition in the code function and add the className inline-code to the code tag.

const components = {
  code({ inline, className, children, ...props }: any) {
    const match = /language-(\w+)/.exec(className ?? "");

    if (inline) {
      return (
        <code {...props} className="inline-code">
          {children}
        </code>
      );
    }

    return match ? (
      <SyntaxHighlighter
        language={match[1]}
        PreTag="div"
        children={String(children).replace(/\n$/, "")}
        {...props}
      />
    ) : (
      <code className={className} {...props} />
    );
  },
};

return (
  <ReactMarkdown components={components} remarkPlugins={[gfm]}>
    {content}
  </ReactMarkdown>
);

Then in your css you can add the styles necessary to highlight the text.

.inline-code {
    display: inline-block;
    padding: 2px 4px;
    color: #232629;
    background-color: #e3e6e8;
    border-radius: 3px;
}