Published on

ReactMarkdownにシンタックスハイライトを適用する方法

Authors
  • avatar
    Name
    ssu
    Twitter

ReactのMarkdownにシンタックスハイライトを適用する方法

ReactMarkdownを使っていてそのcodeに対して、シンタックスハイライト(syntax-highlight)を適用する際に手こずったので、備忘録として残します。(このブログも同様の方法でsytanx highlitを適用しています。)

使うライブラリは、react-syntax-highlighter なので、 まずは、インストールします。

yarn add react-syntax-highlighter

次に下記のコードのようにMarkdownにハイライトするcomponentsを追加すると codeにsyntaxハイライトが適用されるようになります。

また気をつけないといけないのは、import { tomorrow } from 'react-syntax-highlighter/dist/cjs/styles/prism' です。ESMを使っている場合は、import { tomorrow } from 'react-syntax-highlighter/dist/esm/styles/prism'にしてください。

import ReactMarkdown from 'react-markdown' import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter' import { tomorrow } from 'react-syntax-highlighter/dist/cjs/styles/prism' const components = { code({ node, inline, className, children, ...props }) { const match = /language-(\w+)/.exec(className || '') return !inline && match ? ( <SyntaxHighlighter style={tomorrow} language={match[1]} PreTag="div" {...props}> {String(children).replace(/\n$/, '')} </SyntaxHighlighter> ) : ( <code className={className} {...props} > {children} </code> ) }, } const App = () => { const markdown = `Here is some JavaScript code: ~~~js console.log('It works!') ~~~ ` return ( <ReactMarkdown components={components}>{markdown}</ReactMarkdown> )

参考: react-markdown#use-custom-components-syntax-highlight