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?

[React]hoverで表示するツールチップなどはstateを使わずに切り替えるべし

Last updated at Posted at 2024-01-26

【React】ツールチップにuseStateはいらない!

💡 結論

ホバーでツールチップを表示するだけなら、useStateは使わずにCSSで解決できます!


❌ よくある失敗パターン(useStateで制御)

const [isHover, setIsHover] = useState(false)

return (
  <div
    onMouseOver={() => setIsHover(true)}
    onMouseLeave={() => setIsHover(false)}
  >
    {isHover && <div>ツールチップ</div>}
  </div>
)

問題点

  • マウス移動が速いと表示がうまくいかない
  • 要素ごとにstateを用意するとコードが冗長に

✅ スマートな方法:CSSだけで解決!

TailwindCSSの場合

return (
  <div className="relative hover:[&>div]:block">
    <button>ボタン</button>
    <div className="hidden absolute top-full mt-1 bg-gray-700 text-white px-2 py-1 rounded">
      ツールチップ
    </div>
  </div>
)

解説

  • hover:[&>div]:block → ホバー時に子要素(ツールチップ)を表示
  • div → 任意の要素に変えてOK(svg, span, など)

🧠 余談:display vs visibility

特性 display: none visibility: hidden
非表示時の領域確保

使い分けの基準として知っておくと便利です!


🎯 まとめ

  • 簡単な表示切替はCSSだけで十分
  • useStateで管理するのは過剰設計
  • Tailwindなどを使えば可読性&保守性もアップ

閲覧ありがとうございました!
次のUI改善にもぜひCSSトリックを活かしてみてください ✅


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?