LoginSignup
8
3

More than 3 years have passed since last update.

react + marked + highlight の設定や拡張

Last updated at Posted at 2019-12-06

はじめに

いなたつアドカレの六日目の記事です。

今回は前回に続いてMarkdownをReactで表示するために、htmlに変換する部分です。
あとは、シンタックスハイライトをする方法ですね。

じっそー

まずはインポートとインスタンスの生成

import marked from 'marked';
import hljs from 'highlightjs'
import 'highlightjs/styles/monokai.css' // monokaiの場合
const r = new marked.Renderer()

そして、markedの拡張(変更)

// h1,h2,h3 ....
r.heading = (text, level) => {
    let escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
    return (
        `
            <h${level}>
                ${text}
            </h${level}>
        `
    )
}

h1などのタグの拡張です。
rは先ほどインスタンス化したものですね。
headingがh1,h2などのタグにあたります。

これを使うことで、指定したclass名を付与し、cssによる管理が可能になります。

このほかにも様々な記法をHTMLタグに変換する過程で拡張できます。

以下が拡張できるものです(公式リファレンス参考)

ブロック要素

  • code(string code, string infostring, boolean escaped)
  • blockquote(string quote)
  • html(string html)
  • heading(string text, number level, string raw, Slugger slugger)
  • hr()
  • list(string body, boolean ordered, number start)
  • listitem(string text, boolean task, boolean checked)
  • checkbox(boolean checked)
  • paragraph(string text)
  • table(string header, string body)
  • tablerow(string content)
  • tablecell(string content, object flags)

インライン要素

  • strong(string text)
  • em(string text)
  • codespan(string code)
  • br()
  • del(string text)
  • link(string href, string title, string text)
  • image(string href, string title, string text)
  • text(string text)

次にインポートしたmarked本体の設定で、。これでhighlight.jsを有効にできます

marked.setOptions({
    highlight: function (code, lang) {
        return hljs.highlightAuto(code, [lang]).value;
    }
});

そして、以下のようにすることで、markdownをhtmlに変換します

marked(md, { renderer: r })

mdに入ってる値をmarkedを使って変換しています。ここをstateなどを指定することで、reactっぽくなりますね。

最後に前回と組み合わせて、stateのbodyに格納されたmarkdownをhtmlに変換しコンポーネント内部に展開して表示する部分を記しておきます。

<span dangerouslySetInnerHTML={{ __html: marked(state.body, { renderer: r }) }} />

以上がreact + markedown + highlight の使い方になります。

8
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3