2
2

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.

<a>タグ内で遷移させずにクリックイベントを実装する簡単な方法

Posted at

どうもこんにちは、たくびー(@takubii)です。

Reactで<a>タグ内の特定の要素で遷移せずにクリックイベントを起こす実装したので方法を共有します。
特に難しいことはないのですが、備忘録として残します。

結論

preventDefault()を使うです。

リンク遷移したくない要素の関数の先頭でpreventDefault()を宣言すればイベントの発生を抑制できるので、それを使用しました。

実装

簡単に実装例を記載します。

export const MyComponent = () => {
  const handleClick = (e) => {
    e.preventDefault();
    // 何かの処理
  };

  return (
    <a href='/test'>
      <div>この部分はクリックすると/testに遷移する</div>
      <div onClick={(e) => handleClick(e)}>この部分はクリックしても遷移しない</div>
    </a>
  );
};

終わりに

簡単な内容ですがこの情報があなたのお役に立てたら幸いです。

ReactもJSですが、単純なクリックイベントの取得方法とかは忘れやすいのでこういった形で残しておこうと思います。

それではまた機会があればお会いしましょう。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?