Home
Blog
Products
Profile
Study
Collatz
© 2024 Oizumi Yuta

【React】react-markdown にシンタックスハイライトを追加する

2024-12-15

概要

このブログ記事のレンダリングを SSR から CSR に移行した(前回の記事に書いた)。CSR に移行した恩恵として、マークダウンにシンタックスハイライトが可能になった。今回はその手順を書く。

なおマークダウンは react-markdown を使用している。

手順

インストール

使用するのは以下のパッケージ:

  • react-syntax-highlighter
npm react-syntax-highlighter
npm i --save-dev @types/react-syntax-highlighter

実装

import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
import { vscDarkPlus as codeTheme } from 'react-syntax-highlighter/dist/esm/styles/prism';

const markdown = `
# サンプルMarkdown

\`\`\`js
function helloWorld() {
  console.log("Hello, world!");
}
\`\`\`

\`\`\`python
def hello_world():
    print("Hello, world!")
\`\`\`
`;

const Markdown = (props: { content: string }) => {
  return (
    <div className={styles.content}>
      <ReactMarkdown
        remarkPlugins={[remarkMath, remarkGfm]}
        rehypePlugins={[rehypeKatex]}
        components={{
          a: ({ node, ...props }) => (
            <a {...props} target="_blank" rel="noopener noreferrer">
              {props.children}
            </a>
          ),
          code: ({ className, children }) => {
            const match = /language-(\w+)/.exec(className || '');
            return match ? (
              <SyntaxHighlighter language={match[1]} style={codeTheme}>
                {String(children).replace(/\n$/, '')}
              </SyntaxHighlighter>
            ) : (
              <code className={className} {...props}>
                {children}
              </code>
            );
          },
        }}
      >
        {markdown}
      </ReactMarkdown>
    </div>
  );
};

動作確認

image

使用可能なシンタックスハイライト一覧

AVAILABLE_STYLES_PRISM.MD

参考

  • https://goodlife.tech/posts/react-markdown-code-highlight.html
  • https://techblg.app/articles/react-syntax-highlighter-markdown/