Open In App

React Spring Introduction and Installation

Last Updated : 08 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React Spring is an animation library that makes animating UI elements simple. 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 the browsers.

Prerequisites:

Preview of final output: Let us have a look at how the final output will look like.

Steps to create React Application And Installing Module:

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:

Project Structure.

Example: I have used the useSpring hook that takes an object reflecting how the animation should unfold. To apply these props we have to use the extended versions of elements defined in the animated module. We will be creating a component LoopingCard which rotates on its z-axis. The App.jsx is the main component that uses the LoopingCard component.

Javascript




import React from 'react'
import LoopingCard from './LoopingCard'
 
function App() {
    console.log('hello')
    return (
        <>
            <LoopingCard />
        </>
    );
}
 
export default App;


Javascript




//LoopingCard.js
import React from 'react';
import { useSpring, animated } from 'react-spring'
 
const LoopingCard = () => {
 
    /**
     * Define the style for the animation
     * using the useSpring hook
     */
    const styles = useSpring({
        loop: true,
        from: { rotateZ: 0 },
        to: { rotateZ: 360 },
        duration: 2000,
    });
 
    /**
     * Animated div is the extended version of div that
     * accepts the properties defined above.
     */
    return (<animated.div
        style={{
            width: 80,
            height: 80,
            backgroundColor: 'd6d6d6',
            borderRadius: 16,
            boxShadow: 'rgb(0,0,0,0.44) 0px 5px 5px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            color: 'green',
            margin: 250,
            ...styles,
        }} >GFG</animated.div>
    );
}
 
export default LoopingCard;


Step to Run the Application: Run the following command.

npm start

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads