📝

tailwindcssとreact-md-editorでマークダウンを表示する

2025/03/26に公開

tailwindcssをつかっているプロジェクトに@uiw/react-md-editorを導入したら、思ってた見た目にならなかったのでメモ。

スタイルが適用されない

@uiw/react-md-editor を読んでエディターコンポーネントをつくるとこういうコードになるが、

editor.jsx
import MDEditor from "@uiw/react-md-editor";
import rehypeSanitize from "rehype-sanitize";
import "@uiw/react-md-editor/markdown-editor.css";
import "@uiw/react-markdown-preview/markdown.css";

return(
    <div className="container">
        <MDEditor
            value={value}
            onChange={setValue}
            previewOptions={{
                rehypePlugins: [[rehypeSanitize]],
            }}
        />
    </div>
)

このようにマークダウンのプレビュー表示時にリストにスタイルがあたっていない見た目になってしまった。リストの表示がめっちゃ変。

cssをimportしているが、tailwindのpreflightによるresetによってリストのスタイルは消されてしまっている模様。

importしているcssの中身をコピペしてglobal.cssにベタ書きして上書きしたりすれば無理やり適用できそうだけど、できればやりたくない。

外部からスタイルを当てるのは諦めてtailwindcss/typographyを使う

@tailwindcss/typography

という文章をいい感じに表示するプラグインがあると知ったので、tailwindに従うことに。

パッケージをインストールしたら

global.css
@import "tailwindcss";
@import "tw-animate-css";
+ @plugin "@tailwindcss/typography";
tailwind.config.js
module.exports = {
	...// 略
	plugins: [require("@tailwindcss/typography")],
};

global.cssとtailwind.config.jsにこのように設定を追加して、classに"prose"を追加するだけ。

editor.jsx
import MDEditor from "@uiw/react-md-editor";
import rehypeSanitize from "rehype-sanitize";

return(
    <div className="container prose">
        <MDEditor
            value={value}
            onChange={setValue}
            previewOptions={{
                rehypePlugins: [[rehypeSanitize]],
            }}
        />
    </div>
)

とりあえずプレビューがいい感じに表示されるようになった。
が、なぜかエディタ側の文字がめちゃ薄いグレーになってしまった。

proseをプレビューにだけ適用する

エディタのプレビューコンポーネントの構造はcomponentsOptionで指定できるらしいので以下のように修正。

editor.jsx
import MDEditor from "@uiw/react-md-editor";
import rehypeSanitize from "rehype-sanitize";

<div className="container">
    <MDEditor
        value={value}
        onChange={setValue}
        previewOptions={{
            rehypePlugins: [[rehypeSanitize]],
        }}
        components={{
            preview: (source, state, dispatch) => {
                return (
                    <div className="prose">
                        <MDEditor.Markdown source={source} />
                    </div>
                );
            },
        }}
    />
</div>

無事にプレビューにだけスタイルが当たるようになった。

Discussion