1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

microCMSのリッチエディタ内をCSSで装飾する方法【html-react-parser】

Posted at

MicroCMSのリッチエディタで作成されたHTMLをReactで扱う際、特定のタグだけにスタイルを当てたいことがあります。

スクリーンショット 2025-06-30 20.17.11.png

この記事では、Next.jsプロジェクトでhtml-react-parserreplaceを使って、例としてh2・h3タグを装飾する方法を紹介します。

前提

  • Next.jsを使用したプロジェクト
  • microCMSのリッチエディタからHTMLを取得
  • スタイリングにTailwind CSSを使用

html-react-parser

html-react-parserは、HTML文字列をReactのコンポーネントに変換するライブラリです。これを使うと、外部から取得したHTML(例えばCMSのリッチテキスト)を表示できます。

parse

parseは、html-react-parserのメイン関数で、HTML文字列を受け取ってReact要素として変換します。オプションでreplaceなどを渡して変換処理を追加できます。

DOMNode

DOMNodeは、HTMLの各要素(ノード)を表す型で、タグ・テキスト・コメントなどの情報を持ちます。replace関数の中で、渡されたノードがタグかどうかなどを判定するのに使います。

replace

replacehtml-react-parserのオプションの一つで、特定のタグやノードを検出して、任意のReact要素に置き換えることができます。h2やh3だけにクラスを当てるなど表示のカスタマイズが可能になります。

replaceオプションでタグ名を検出してクラスを付与します。

import parse, { DOMNode, domToReact } from "html-react-parser";
import { Element as DomElement } from "domhandler";

parse(work.body, {
  replace(domNode: DOMNode) {
    if (domNode.type === "tag" && (domNode as DomElement).name === "h2") {
      const el = domNode as DomElement;
      return (
        <h2 className="text-xl mt-8 mb-2 font-bold text-blue-700">
          {domToReact(el.children as unknown as DOMNode[])}
        </h2>
      );
    }
    if (domNode.type === "tag" && (domNode as DomElement).name === "h3") {
      const el = domNode as DomElement;
      return (
        <h3 className="text-lg mt-6 mb-1 font-semibold text-blue-500">
          {domToReact(el.children as unknown as DOMNode[])}
        </h3>
      );
    }
  },
});

こうするとリッチエディタで作成されたHTML内にもスタイルを当てることができます。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?