![1分でできるreact-springのアニメーション実装方法](https://iwb.jp/wp-content/uploads/2024/05/react-spring-use-spring-animated.png)
react-springとは
Reactアプリケーションでアニメーションを実装するための人気ライブラリです。
物理法則に基づくアニメーションを簡単に作成でき、柔軟でパフォーマンスの高いアニメーションを実現することができます。
react-springの使い方
まず、Reactの開発環境で「npm i @react-spring/web」でインストールします。
ShellScript
npm i @react-spring/web
次に以下のようにuseSpring, animatedをimportして、useSpringにはCSSのプロパティやアニメーションの設定をします。
最後にanimated.divコンポーネントにスタイルを適用することで、アニメーションが実行されます。
TSX
import { useSpring, animated } from '@react-spring/web'
export default function App() {
const props = useSpring({ opacity: 1, from: { opacity: 0 } })
return <animated.div style={props}>Hello!</animated.div>
}
もし、以下のようなボタンがあってクリックした際にopacityを0から1にして、xとyを100px移動して遷移させたい場合は…
TSX
export default function App() {
return (
<>
<button>click</button>
<div style={{
width: 100,
height: 100,
background: '#CC0000',
}}></div>
</>
)
}
次のようにuseSpring, animatedをimportして、useStateを使用してuseSpring内のプロパティの値を切り替えます。
TSX
import { useState } from 'react'
import { useSpring, animated } from '@react-spring/web'
export default function App() {
const [toggle, setToggle] = useState(false)
const styles = useSpring({
opacity: toggle ? 1 : 0,
x: toggle ? 100 : 0,
y: toggle ? 100 : 0,
from: { x: 0, y: 0 },
})
return (
<>
<button onClick={() => setToggle(!toggle)}>click</button>
<animated.div
style={{
width: 100,
height: 100,
background: '#CC0000',
...styles,
}}
/>
</>
)
}
react-springを使用すれば、次々とずらすようなアニメーションやパララックスアニメーションなども簡単に作成できます。