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

More than 5 years have passed since last update.

[React+Storybook]KnobsでdangerouslySetInnerHTMLがうまく表示されないとき

Last updated at Posted at 2020-02-27

現象

Reactで(Vueもだと思うけど)Storybook + Knobsのスタックで、Knobsのtext()にHTMLタグを直接渡して、コンポーネントでdangerouslySetInnerHTMLを使ってレンダリングしようとするとうまく行かない。

Screen Shot 2020-02-27 at 15.45.04.png

原因

Knobsのtext()にHTMLタグを渡すと、親切にタグをエスケープしてくれるらしい。

<p>こんにちは!<br><br>はじめまして<br><br>さようなら</p>

対応

ただアンエスケープするだけでよし。

export const onlyParagraph = () => {
  const beforeContent = text(
    "content",
    "<p>こんにちは!<br><br>はじめまして<br><br>さようなら</p>"
  );

    // Knobsのtext()でHTMLタグがエスケープされてしまうので、アンエスケープしています
    const unescapeHtml = string => {
      const patterns = {
        "&lt;": "<",
        "&gt;": ">",
        "&amp;": "&",
        "&quot;": '"',
        "&#x27;": "'",
        "&#x60;": "`"
      };

      const escapedString = string.replace(
        /&(lt|gt|amp|quot|#x27|#x60);/g,
        match => patterns[match]
      );

      return escapedString;
    }

  return (
    <>
      <HTMLContentWrapper content={unescapeHtml(beforeContent)} />
    </>
  );
};

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