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 + tailwindCSSで簡単にアコーディオン開閉アニメーションを実装

Last updated at Posted at 2025-02-03

簡単なtailwindとJSでアコーディオンの開閉アニメーションの実装記事がなかなか見つからなかったので、自分なりに実装してみました。

実装

const [isOpen, setIsOpen] = useState<boolean>(false);

return (
  <>
    <div onClick={() => setIsOpen(!isOpen)}>
      <p>タイトル</p>
    </div>
    
    <div className="grid duration-300 ease-in-out ${isOpen ? 'grid-rows-[1fr]' : 'grid-rows-[0fr]'}">
      <div className="overflow-hidden">
        <p>本文本文本文本文本文本文本文</p>
      </div>
    </div>
  </>
)

実装結果

GIF画像だとちょっと速く見えますが、実際はもうちょっとぬるっと開いて閉じます。

ダウンロード.gif

durationの秒数を増やせば遅くなるし、減らせば速くなります。

まとめ

アコーディオンの開閉アニメーションは、jQueryやjavascriptで高さを取得して...といった手法はやったことはあるけど、CSSだけで実装できるのは初めてでした。
tailwindは便利で好きだけど、アニメーションになってくるとどのクラスを適用したらいいのか自分は少し分かりづらい(苦手)かもと思いました。

参考記事

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?