1
0

More than 1 year has passed since last update.

Reactのbutton要素内でFont Awesomeアイコンを使う時の注意点

Last updated at Posted at 2022-03-01

目的

クリックイベントで関数を呼び出すボタン要素の中にFont Awesomeコンポーネントを使ってアイコンを表示させたい。
しかしなぜか指定したnameがundefinedになってしまう...

samples.map( sample => {
    return (
        <button onClick={handle} name={sample.id} className="border-0">
              <FontAwesomeIcon icon={faTrashCan} />
        </button>
    )

const deleteMemo = (e) => {
        const id = e.target.name //undefined...
        console.log(id); //undefined...?
        axios
            //割愛

原因

以下のようにevent.targetをコンソールに表示してみたところ、

const handle = (e) => {
    console.log(e.target)
}

Font Awesomeコンポーネントの内容(svg)がevent.targetになっていた。

<svg aria-hidden="true" focusable="false" data-prefix="far" data-icon="trash-can" class="svg-inline--fa fa-trash-can" role="img"></svg>

解決法

Font Awesomeコンポーネントにcssを当ててeventが発火しないように変更

pointer-events: none;

自分はemotionを使っているのでとりあえず以下のように記述したところ想定の挙動をするようになりました。

<button onClick={handle} name={sample.id} className="border-0">
        <FontAwesomeIcon css={css`pointer-events: none;`} icon={faTrashCan} />
</button>

svg要素にonclick属性がついてるの初めて知った...

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