3
2

【React】react-springでいい感じのアニメーションをつくる

Posted at

はじめに

画面のコンテンツに良い感じの動きをつけたいな~と思って調べていたところ、簡単に動きを試せそうなライブラリを見つけたので触ってみました。

やりかた

まずは公式サイトのチュートリアル通りに進めてみます

import { useSpring, animated } from '@react-spring/web'

export default function MyComponent() {
  const springs = useSpring({
    from: { x: 0 },
    to: { x: 100 },
  })

  return (
    <animated.div
      style={{
        width: 80,
        height: 80,
        background: '#ff6d6d',
        borderRadius: 8,
        ...springs,
      }}
    />
  )
}

チュートリアルでは上のコードがサンプルとして記載されていました
画面にアクセスすると図形が左からスライドしてくるアニメーションを確認できると思います

これに少し手を加えて、左右にスライド&無限ループさせてみたいと思います

import { animated, useSpring } from '@react-spring/web'

export default function MyComponent() {
    const springs = useSpring({
        from: { x: 0 },
        to: async next => {
            while (true) {
                await next({ x: 100, config: { duration: 1000 } })
                await next({ x: 0, config: { duration: 1000 } })
            }
        }
    })

    return (
        <animated.div
            style={{
                width: 80,
                height: 80,
                background: '#ff6d6d',
                borderRadius: 8,
                ...springs,
            }}
        />
    )
}

ポイント

  • useSpringでアニメーションの状態を定義
  • 今回は画面上で常に動かすため、非同期で動きをつける
  • animated.divというコンポーネントにuseSpringとstyleを渡す

おわりに

公式サイトに色々なアニメーションがサンプルコード付きで紹介されているので手軽に試すことができました!

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