Facebook EmaiInACirclel
Front-end, back-end development

Build Elegant Web Animations with React Spring

Jensen Baronville
Jensen Baronville
Front-end Developer

There are many, many ways to create all types of web animations. Lots of developers use CSS and add classes to HTML tags in order to build them. But, to create some truly stunning products I suggest trying React Spring’s animation libraries and components.

“Anima” is the Latin word meaning life & intelligence. Animation is important because it helps artists communicate concepts in a way that appeals to viewer emotions. Creating animations is an art form that gives life to otherwise static objects. I believe any great front-end developer should hone the skill of creating web animations.

In this article, I’ll be showing you how to “animate apps” and build the basic skillset to be able to develop a project like the one below.

React Spring

Check out the code.

Did you Know? Animations help build user trust in your product!

As developers, we’re in charge of creating an experience for users – and web animations are one of the tools we use to immerse them in the environment we’ve created. But, to do that successfully – we have to switch over to the mindset of a user. So, how do we do that?
 

Here are some useful tips to help you switch over to a user mindset:

  • 1. Focus on guiding the user through the entire experience.

Our aim is avoid distracting the user with our animations. They should help, not hinder. So, we should try to build as natural a flow as possible. This way, users will focus on the most important information and actions.

  • 2. No animation is better than bad animation.

Creating animation is not just about moving things around and putting things in for show. If it detracts from your message, it’s best to leave it out completely.

  • 3. Don’t put web animation onto a site to just follow a trend.

Motion and design in programing should be used with the goal to solve problems. Not because it just looks good on your website.

Now that we’ve got the “theory” out the way, let’s dive into the technical part and talk about web animations with React Spring.
 

React Spring – “The Tool”

Developers can create amazing animations using frames, such as CSS and VanillaJS.

“Frames” are individual pictures in a sequence of images. They are a bit tricky to manage, so a little patience goes a long way when building them.  Using the wrong tool or framework is any developer’s worst nightmare. Doubly so when it comes to web animations, because they require complex UI element manipulations. This is exactly why I want to share more about my experience with React Spring.

React Spring is a spring-physics based animation library that covers most UI related animation needs.

I personally love how their team describes the tool online. “React Spring gives you tools flexible enough to confidently cast your ideas into moving interfaces.”

This library is a great option if you’re looking to become a digital artist. You only need to write small pieces of code to produce some impressive results. And, while it’s not perfect – it is a great library option for problem solving and creating beautiful animations.

 

Some of the benefits of the React Spring library are:

  • More Intuition

You only need to understand simple physics concepts to predict how your animation will behave.

  • Cleaner Code

React Spring was designed for the purpose of writing cleaner code, so it allows developers to create amazing animations without investing much effort.

  • Enhanced Performance

React Spring is both developers and computer-friendly, so there’s no need to worry about your project becoming slower after adding animations.

  • Responsive

If you want to create mobile experiences, this library will adapt perfectly to your needs.

 

Learn these 3 basics to create beautiful web animations:

1. Config & Config presets

The core config of our animations.

2. Hooks

The functions that we will use to declare our animations.

3. The animated component

The component we need to animate.
 

1. Config & Config presets

The config is the set of physical properties we want to give to our Spring – so you only need to remember how Spring behaves in the real world.

config React Spring
 
A spring has the following physical properties:

  1. Mass – The higher the mass, the longer it takes for the animation to come to a rest.

  2. Tension – If the spring’s tension is high, the spring will contract more powerfully, and the animation will feel snappy.

  3. Friction -The higher the friction, the slower an animation will be.

  4. Precision – By keeping precision low, the animation will be more accurate and might take longer to reach equilibrium.

  5. Velocity – The speed with which you push the gravity center is the velocity. Pushing downwards is a negative velocity, pushing upwards is a positive velocity.

  6. Clamp – There will be no bounce and the animation will come to a stop immediately.

The implementations of each prop in the config should be done as in the code below:

import { useSpring } from ‘react-spring’

useSpring({ …, config{ mass: 1, tension: 170, friction: 26 } })

To make your life even easier, you can use a tool called React-spring-visualizer. This app helps you experiment with the config visually without writing a single line of code, so you can have a better idea of what is going to happen with your animations even before opening your code editor.

React Spring Visualizer

Config Presets

React Spring comes with a set of sweet presets.

Presets are pre-built configs that will cover some common ground.

  • config.default
  • config.gentle
  • config.wobbly
  • config.stiff
  • config.slow
  • config.molasses

To implement your presets, you only need to do the following:

import { ..., config } from 'react-spring'

//We will use default but can use any other preset.

useSpring({ ..., config: config.default })

 

2. Hooks

Let’s get our hands dirty implementing some animations. The great thing about this library is that it uses React Hooks to make your coding experience even easier.

This library has 5 main hooks to create beautiful web animations. Something important to mention is that in this library the unit of animation is called Spring.

Helps us to create animation with a single spring.

Helps us to create animation with multiple springs.

Helps us to create a trail of springs.

Helps us to create transitions.

Is a queue or chain for multiple animations together

 

To create our springs, we will need to understand the following 3 things (config, spring values, from & to)

  • config

The physical prop of our spring ****

  • spring values

Spring values are the elements we want to animate. Our values can be strings, numbers, booleans, and css props like colors and percentages.

  • from & to

If we want to add initial values to start animations automatically, we can use an object with spring values called “from” and “to” will be an object with the final values of our animation, so this 2 props together are like from point A go to point B.

useSpring

This hook helps us create a simple Spring.

import React from "react";

import { useSpring, config } from "react-spring";

const Spring = () => {

const [size, setSize] = React.useState(100); //everythime

const animatedStyles = useSpring({

config: config.slow, //Default preset

width: size, //numeric value - css value

height: size - 50, //numeric value - css value

border: "1px solid black", //string value - css value

background: "purple" //string value - css value

numberToAnimate: "purple" //string value - css value

 

from: {..., width: 100} //inital animation

to: {..., width: 100} //inital animation

 

});

 

return (

<>

...

</>

);

};

 

 

3. The Animated Component

This library uses a special component to help us with performance – it is called animated. This component will be used to create our animated views. If you have experience with style components or emotion, then using this component should feel familiar to you.

import { animated } from "react-spring";

 
// React components

const AnimatedDonut = animated(Donut)

 
// React-native

const AnimatedView = animated(View)

 
// styled-components, emotion, etc.

const AnimatedHeader = styled(animated.h1)`

 
//Regular usage

const AnimatedComponent = () => <animated.div> Animation here </animated.div>

Make sure to extend the native element you want to animate using “animated”. If your target is the web, then animated contains all valid html elements (divs, spans, svgs, etc).

 

The Final Result

Now, let’s put it all together:

import React from "react";

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

 
const Spring = () => {

const [size, setSize] = React.useState(100);

const animatedStyles2 = useSpring({

config: config.slow, //Default preset

width: size,

height: size - 50,

border: "1px solid black",

background: "purple"

});

 
const animatedStyles = useSpring({

config: config2,

to: [

{opacity: 0, color: "rgb(14,26,19)" }

],

from: { opacity: 0, color: "red", number: 0 }

});

 
return (

<>

<animated.div onClick={() => setSize(size + 100)} style={animatedStyles2}>

<animated.h1 style={animatedStyles}>

{animatedStyles.number}

</animated.h1>

</animated.div>

</>

);

};

 
export default Spring;

 

Bringing It All Together

React Spring is a great library to build solid, clean animated UIs. In some cases, you might need to refactor your components that make your animations possible. In other cases, you will only need to declare custom hooks.

On your next project, try embracing a more simple, elegant solution for your animations using just hooks and an intuitive preset list – without sacrificing control or function. Try using only presets configs and make small animations to guide your users through the entire experience.

A good thing about this module is that almost everything is already set up for you and you can re-use a lot of components in multiple projects.

If you want to learn more about React Spring, go to the official docs. I also highly recommend you watch the introductory videos made by its creator:

Docs: https://www.react-spring.io/

Video: https://www.youtube.com/watch?v=1tavDv5hXpo&feature=emb_title

Remember, the best way to learn is to experiment and work on projects. So, I recommend you built a sandbox with some basic springs and hooks to let you experiment with React Spring.

Good luck & happy creating!


Leave a Reply

Your email address will not be published. Required fields are marked *

mypentalog

Always, Everywhere.
Our teams are here for you.