1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ブラウザ上に表示されたHTMLタグをreact-markdownを利用して消去する

Posted at

はじめに

現在Next.js×TypeScriptでアプリを作成中です。
初めてreact-markdownを使用したのでメモします。

問題

microCMSから取得したブログのcontentをブラウザ上に表示すると、下記のようにhtml要素のpタグも一緒に表示されてしまいます。

image.png

解決方法

react-markdownを使用して簡単に解決していきます。
react-markdownとは、Reactコンポーネントの一種で、Markdown文字列を安全にReact要素にレンダリングすることができるみたいです。

インストールします。
今回はrehype-raw というプラグインも併せてインストールしますが、これがないとHTML要素を認識できないようです。

npm install react-markdown rehype-raw

サンプルは下記になります。

page.tsx
<div className="text-gray-600">
  <ReactMarkdown rehypePlugins={[rehypeRaw]}>{content}</ReactMarkdown>
</div>

pタグの表示が消えています。

image.png

おわりに

最初はdangerouslySetInnerHTMLを使用して解決を試みていたのですが、"Text content does not match server-rendered HTML"(サーバー側とブラウザ側でのレンダリングにずれが発生したときに出るエラー)が出てしまいました。
あれこれ時間をかけて試行錯誤しましたがpタグが消えることはなく、react-markdownを使ってみたらすんなり解決できました。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?