How to create animations in React with React Spring

How to create animations in React with React Spring

In this article we’ll be exploring one of the best animation frameworks for React: React Spring...

Animations has evolved to very complicated UI element manipulations. They are used to increase interactivity on web pages and to give users an engaging experience while using websites. Developers are constantly looking to find better ways to implement animations without causing a major performance bottleneck.

Animation effects are applied on the UI thread which is usually called frequently, as a result, adding certain animations/animation libraries could have negative impacts on your site. This is why we have chosen to discuss React Spring as a tool you should consider using to animate your React apps.

Prerequisites

React Spring has both a hooks-based and a component-based API, we’ll be exclusively looking at using hooks with basic state for all our animations. So if you need some brushing up on React Hooks, I recommend this article.

Installation and Setup

Of course, we’re going to need react-spring, and we can just use Create React App to get started.

$ npx create-react-app react-spring-example
$ cd react-spring-example
$ npm i react-spring 

From and To

In our App.js file we’re going to need useSpring and animatedfrom react-spring.

useSpringis a custom hook that we can set our style to, it takes an object with the from and to values as the start and end states while react-spring handles the transition between them. from and to can take objects of almost every css property: color, size, transform, and even our scrollbar. To apply our spring animation, we just need to add animatedonto our HTML tags and pass our animation to our style. By default this is run as soon as the component is mounted.

Going from one value to another is maybe a little boring, but react-spring lets us use arrays to render animations with multiple stages. Just remember to always include the starting state with any property you want to add.

import React, { useState } from 'react';
import { useSpring, animated } from 'react-spring';


const App = () => {
  const animation = useSpring({
    from: { opacity: 0 },
    to: { opacity: 1 }
  });

  const colorAnimation = useSpring({
    from: { color: 'blue' },
    to: { color: `rgb(255,0,0)` }
  });

  const multiAnimation = useSpring({
    from: { opacity: 0, color: 'red' },
    to: [
        { opacity: 1, color: '#ffaaee' },
        { opacity: 1, color: 'red' },
        { opacity: .5, color: '#008000' },
        { opacity: .8, color: 'black' }
    ]
  });
  return (
    <div>
      <animated.h1 style={animation}>Hello World</animated.h1>
      <animated.h1 style={colorAnimation}>Hello World</animated.h1>
      <animated.h1 style={multiAnimation}>Hello World</animated.h1>
    </div>
  )
};

export default App;

State

Adding some local state will allow us to add some actual interactions to our animations, instead of transitioning on mount. Instead of from and to we can use a ternary operator for our single step animations.

import React, { useState } from 'react';

const App = () => {
  const [on, toggle] = useState(false);

  const animation = useSpring({
    color: on ? 'blue' : 'red'
  });
  return (
    <div>
      <animated.h1 style={animation}>{!on ? "I'm red" : "Now I'm blue" }</animated.h1>
      <button onClick={() => toggle(!on)}>Change</button>
    </div>
  )
};

Interpolate

Besides only adding static style changes to our elements and components we can create more interesting and reusable animations using the interpolate method. We can add variables to our spring, since it is also an object, and use interpolate to extract them for our styles.

We just need to extract our value from our spring and use interpolate to destructure it some more, throw them into some template literals and we’re good to go. This will allow us the freedom to set more dynamic values, like a color value that is based on the x position.

const App = () => {
  const [on, toggle] = useState(false);

  const { xy } = useSpring({
    from: { xy: [0, 0], color: 'green' },
    xy: on ? [800, 200] : [0, 0],
    c: 'red'
  });
  return (
    <div>
      <animated.h1
        style={{ 
            transform: xy.interpolate((x, y) => `translate(${x}px, ${y}px)`), 
            color: c.interpolate(c => c)}}>
        {!on ? "I'm here" : "Now I'm over here"}</animated.h1>
      <button onClick={() => toggle(!on)}>Change</button>
    </div>
  )
};

Mimicking Keyframes

One of the more useful aspects of interpolate is that we can emulate CSS keyframes. Instead of passing a value into our spring, we’ll just set it to 1 or 0. Before we can interpolate it like before, we need to pass in an object with arangeand an output. Range can be any value between 0 and 1 and works like setting breakpoints with CSS keyframes, the corresponding output is the value that will be prerendered.

A second interpolate will then reset our style at every change in output.

const App = () => {
  const [on, toggle] = useState(false)

  const { x, c } = useSpring({
    from: { xy: [0, 0], c: 0 },
    x: on ? 1 : 0,
    c: on ? 1 : 0
  })

  return ( 
    <div>
      <animated.h1
        style={{
          transform: x.interpolate({
            range: [0, .25, .5, .75, 1],
            output: [0, 500, 200, 800, 500]
          }).interpolate(x => `translateX(${x}px)`),

          color: c.interpolate({
            range: [0, .5, 1],
            output: ['red', 'blue', 'green']
          }).interpolate(c => c)
        }}>
        {!on ? "I'm here" : "Now don't know where I'm going"}</animated.h1>
      <button onClick={() => toggle(!on)}>Change</button>
    </div>
  )
}

Config

On its own, the previous example is very abrupt and jarring. This is because of react-spring’s default configuration. The animations are mostly based off of a few properties that we are allowed to easily manipulate in our spring. The docs have a wonderful interactive example that really helps to get an intuitive feel for the different properties.

  • mass: Affects the speed and how far it overshoots the transition.

  • tension: Affects the overall velocity.

  • friction: Controls the resistance and how quickly it decelerates.

  • clamp: Whether it should ever overshoot the transitions.

const animation = useSpring({
    {/* ... */}
    config: {
      mass: 5,
      tension: 50,
      friction: 25,
      clamp: true
    }
  });

To help us out the team at react-spring even included some configuration presets we can import that will be very useful.

  • config.default { mass: 1, tension: 170, friction: 26 }

  • config.gentle { mass: 1, tension: 120, friction: 14 }

  • config.wobbly { mass: 1, tension: 180, friction: 12 }

  • config.stiff { mass: 1, tension: 210, friction: 20 }

  • config.slow { mass: 1, tension: 280, friction: 60 }

  • config.molasses { mass: 1, tension: 280, friction: 120 }

import { useSpring, animated, config } from 'react-spring';

const animation = useSpring({
    {/* ... */}
    config: config.wobbly
  });

// Or you can just destructure it if you want to change other options 
const animation = useSpring({
    {/* ... */}
    config: {
        ...config.molasses, 
        clamp: true
    }
  });

Conclusion

While the examples here may not have been the most flashy, I hope that they are enough to help you understand the basics behind React animations using react-spring.

reactjs

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why ReactJS is better for Web Application Development?

Web Application Development is the point of contact for a business in today's digital era. It is important to choose the right platform for Web Application Development to build a high end Web

ReactJs Course | How to build a YouTube Clone using ReactJS

Hello, this is a new tutorial series about ReactJs. In this series, I will teach you two important topics. First, I will be teaching you what is ReactJs library and why this is so powerful and expandable. We will see what are the important...

Top Reasons to Choose ReactJS for Front-End Development - Prismetric

Why ReactJS is perfect choice for your next web application? Get to know all about ReactJS development and its benefits in detail for frontend development.

ReactJS Web App Development Services

We provide top-notch ReactJS development services to global clients. Hire expert ReactJS developers from top React JS development company, Skenix Infotech.

Highcharts with Reactjs

#reactjs #highcharts #therichpost https://therichpost.com/highcharts-with-reactjs-working-tutorial/ Highcharts with Reactjs Please like, share and subscribe....