In this article, we will learn how to use Events as Objects using React Spring. React spring is an animation library that makes animating UI elements simple. It is based on spring physics which helps it to achieve a natural look and feel. It is different from other animation libraries where someone has to deal with curves, easing, and time durations, all of which are in sync with each other.
Platforms: React spring is a cross-platform library, it supports react, react-native, web, and many more platforms. It also has support for all browsers.
Events as Objects: It is used to create an object with the events like onRest.
Syntax:
useSpring({ from: { x: 0, y: 0 }, onRest: { x: () => console.log('x.onRest'), y: () => console.log('y.onRest'), }, })
Steps to create an app in react.
Step 1: Create a new application using the following command.
npx create-react-app reactspringdemo
Step 2: Now move the created project folder using the following command.
cd reactspringdemo
Step 3: Install the react spring library.
npm install react-spring
Project structure: Import the app folder into the application and after that, the structure will look like this.
Example1: In the below code, we will make use of the above syntax to demonstrate the use of the Events as Objects.
- GFG.jsx
Javascript
import React from 'react' ; import { useSpring, animated } from 'react-spring' function OnRest() { const styles = useSpring({ from: { x: 0, y: 0 }, onRest: { x: () => console.log( 'x.onRest' ), y: () => console.log( 'y.onRest' ), }, }) return ( <animated.div style={{ width: 80, margin: 221, height: 80, backgroundColor: 'green' , borderRadius: 16, ...styles, }} /> ) } export default OnRest; |
- App.js
Javascript
import React from 'react' import GFG from './GFG' function App() { console.log( 'hello' ) return ( <> <GFG /> </> ); } export default App; |
Step to run the Application: Open the terminal and type the following command.
npm start
Output:
Example2: In the below code, we have used a loop to animate an object.
- GFG.jsx
Javascript
import React from 'react' ; import { useSpring, animated } from 'react-spring' function LoopTrue() { const styles = useSpring({ loop: true , from: { rotateZ: 0 }, to: { rotateZ: 180 }, }) return ( <animated.div style={{ width: 80, height: 80, backgroundColor: 'green' , borderRadius: 16, margin: 100, ...styles, }} /> ) } export default LoopTrue; |
- App.js
Javascript
import React from 'react' import GFG from './GFG' function App() { console.log( 'hello' ) return ( <> <GFG /> </> ); } export default App; |
Step to run the Application: Open the terminal and type the following command:
npm start
Output:
Reference: https://react-spring.dev/common/props#events-as-functions