LoginSignup
0
0

Tiptap の bold extension で strong タグの代わりに b タグを使う

Posted at

ただの備忘録

Tiptap では @tiptap/extension-bold を使うことで Bold な文字列に対応することができる。

しかしデフォルトでは全てが strong タグに変換されてしまう。

The extension will generate the corresponding <strong> HTML tags when reading contents of the Editor instance. All text marked bold, regardless of the method will be normalized to <strong> HTML tags.

strong タグは強い重要性を示すものであり、ただの画面上の強調スタイル以上の意味を持つことになる。

自分のユースケースでは相応しくないと感じたので、別のタグで出力したくなった。

extension を extend する

オプションでタグを別のものに変更したりできてもよさそうなものだがそういったオプションはなかった。

ソースコードを見るとそんな難しいものでもなさそうなのでプルリクを投げることも考えたのだが、マージ待ったりするのも面倒臭い...

と思い自前で extension 書くかぁと迷っていたところ、extend できるような設計になっていることを発見した。実に良き

なので、こんな感じで extend してあげれば出力されるタグを任意のものに置き換えることができた。

import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import { Bold } from '@tiptap/extension-bold';

const BtagBold = Bold.extend({
  renderHTML: ({ HTMLAttributes }) => {
    return ['b', HTMLAttributes, 0];
  },
});
const extensions = [
  StarterKit.configure({
    bold: false,
  }),
  BtagBold,
];

const Tiptap: React.FC = () => {
  const editor = useEditor({
    extensions,
    content,
  });
  ......

上記では StarterKit を使っているので、そちらの bold オプションをオフにしておく。

また、HTMLAttributes 周りの mergeAttributes とかをサボっているので、必要な場合はいい感じに調整する必要がある。

参考

ちゃんと使い分けていきたい

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