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】一瞬動くアニメーション?の作り方(Tailwind CSS)

Posted at

概要

React にて、アニメーションを起こす方法の一つとして、自分用メモ。
クラスを切り替える State を使うのはそうだが、setTimeout() で State の値を切り替えることで、一瞬のアニメーションにする。

方法

1.アニメーション用の State と、切り替え用のメソッドを作成
 切り替えはsetTimeoutを使って少し待ってから再度切り替える。

const [animation, setAnimation] = useState(false);

// ボタンクリック時処理
function handleClick() {
  animateBox();
}

// アニメーション処理
function animateBox() {
  setAnimation(true);

  setTimeout(() => {
    setAnimation(false);
  }, 300);
}

2.アニメーション用 State でクラスを切り替える
 変わる前と変わった後のデザインを指定。

{/* クリックすると一瞬で消え、その後ゆっくり現れるアニメーション */}
<div className="flex justify-center items-center size-12">
  <button
    className={`bg-red-500 rounded-xl shadow-[0_0_10px_rgba(0,0,0,0.2)] transform origin-center  ${
      animation
        ? "size-0 opacity-0"
        : "size-12 opacity-100 transition-all duration-1000 ease-in-out"
    } `}
    onClick={handleClick}
  ></button>
</div>;

実際の動き

このやり方で、試しに以下のようなものを作ってみました。
四角がドラッグ&ドロップされたときのアニメーションに使っています。
それっぽい動きを見せたいとき用です。
animation.gif

以上です。

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?