長らく「保存されているplainTextをよしなにリッチにレンダリングする」という要件を仰せつかってきたので、これまでReact上で使ってきたparse系のライブラリをメモとしてまとめてみました。

文字列からリンク検出 - 「react-linkify」

https://github.com/tasti/react-linkify

リンクらしきものを検出して<a></a>タグをレンダーしてくれます。

導入はめっちゃ簡単。JSXでラップするだけ。

import Linkify from 'react-linkify';

<Linkify>See examples at tasti.github.io/react-linkify/.</Linkify>

target=blankにしたい場合は、以下のようにプロパティを付与できる

<Linkify
  componentDecorator={(decoratedHref, decoratedText, key) => (
      <a target="blank" href={decoratedHref} key={key}>
          {decoratedText}
      </a>
  )}
>{message?.text}</Linkify>

emojiの検出 … react-emoji-render

https://github.com/tommoor/react-emoji-render

Slackなどで使われる、:bow: :heart: のような絵文字のショートカットを実際の絵文字に変換・レンダーするためのライブラリ。当然ながら、Slackの独自スタンプなどはレンダーできません。

import { toArray } from "react-emoji-render";

...

const parseEmojis = (value: string) => {
    const emojisArray = toArray(value);

    const newValue = emojisArray.reduce((previous, current) => {
      if (typeof current === "string") {
        return previous + current;
      }
      return previous + current.props.children;
    }, "");
    return newValue;
  };

マークダウンのレンダリング … marked

https://github.com/markedjs/marked