Tutorial

How To Create Animated React Apps With React Spring

Published on December 12, 2019
Default avatar

By Austin Roy

How To Create Animated React Apps With React Spring

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Introduction

Animations add life to your applications and improve the overall user experience. React Spring is an animation package that uses spring-like physics in its core animations to make it easily configurable. Springs are cumulative, meaning they’ll remember all values passed to them.

Reactive slide button

With Spring you are able to:

  • Manipulate values from measurement units to actual data.
  • Manipulate HTML attributes.
  • Manipulate SVG paths.
  • Adjust CSS.

In this tutorial, you will create a sliding and fading animation in a React app using the Spring component of react-spring.

Step 1 — Configuring the Project

You will be setting up the React environment with create-react-app command. This will also generate some boilerplate code that will allow you to get started. To install it, run this command:

  1. npm install -g create-react-app

Now you can use it to create your app:

  1. create-react-app react-spring-demo

A folder named react-spring-demo will be created. Move into that directory and install the react-spring package:

  1. yarn add react-spring

You will notice we’re using yarn as the package manager for this project, as it is the default package manager for create-react-app. Ensure it is installed with the following command:

  1. npm install -g yarn

Now that things are set up, you are ready to create you first animated page.

Step 2 — Animating Styles

Spring can be used to animate styles. In this example you will use it to animate the transition to a newly loaded page. To do this you will wrap the jsx context of App.js in a Spring component.

The Spring component will take two props, from and to, which represent the values to be interpolated by the animation.

In our case we want to create the effect of a page dropping down from above and fading in. The boilerplate generated by create-react-app has the perfect background to show this effect, so you won’t need to change it for now.

To achieve the dropping effect, the initial top margin of the page elements will be set to a negative value and brought to 0 during the animation. To create the fade in effect, you’ll set the initial value of the opacity to 0 and bring that value to 1 at the end of the animation.

This is what the App.js file will look like:

App.js
//
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { Spring  } from 'react-spring';

class App extends Component {
  render() {
    return (

        <Spring from={{ opacity: 0, marginTop: -1000 }} to={{ opacity: 1, marginTop: 0 }}>
          { props => (
            <div  className="App" style={ props }>
              <div >
                <header className="App-header" >
                    <img src={logo} className="App-logo" alt="logo" />
                    <p>
                      Edit <code>src/App.js</code> and save to reload.
                    </p>
                      <a
                        className="App-link"
                        href="https://reactjs.org"
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                      Learn React
                    </a>
                  </header>
                </div>
              </div>
            )
          }
        </Spring>
    );
  }
}

export default App;

Fire up your application by running this command.

  1. yarn start

Your browser will open and you will see the page load with the desired drop and fade in animations.

You can use Spring to create even more animations by adjusting a variety of styles. It is advised to stick to animating opacity and translations to keep your app light.

Step 3 — Animating innerText

You can also use Spring to animate the value of contents shown on the screen. To show this, you will create a counter that starts at 0 and ends at 10 using Spring. from will hold the initial value and to will hold the final value to be displayed.

Under the src directory, create a folder called components. In that directory, create a file called Counter.jsx. Add the following code to Countrt.jsx:

src/components/Countrt.jsx
import React from 'react';
import { Spring } from'react-spring';

const counter = () => (
    <Spring
        from={{ number: 0 }}
        to={{ number: 10 }}
       {props => <div>{props.number.toFixed()}</div>}
    </Spring>
)

export default counter;

Import the counter to App.js and add it under the header element to render it in the app:

App.js
...
import Counter from './components/Counter';

class App extends Component {
  render() {
    return (

        <Spring from={{ opacity: 0, marginTop: -1000 }} to={{ opacity: 1, marginTop: 0 }}>
          { props => (
            <div  className="App" style={ props }>
              <div >
                <header className="App-header" >
                    <img src={logo} className="App-logo" alt="logo" />
                    <p>
                      Edit <code>src/App.js</code> and save to reload.
                    </p>
                      <a
                        className="App-link"
                        href="https://reactjs.org"
                        target="_blank"
                        rel="noopener noreferrer"
                      >
                      Learn React
                    </a>
                    <Counter />
                  </header>
                </div>
              </div>
            )
          }
        </Spring>
    );
  }
}

export default App;

When you open your browser, you will notice the counter under the Learn React text:

Default React page with 10 under the text

The animation is happening so soon that you are missing it while the initial page is animating into visibility. To fix this, you can delay the animation by adding a delay prop as a value in milliseconds. This is the amount of time the animation will wait before starting.

After adding a one second delay, the counter function will now look like this:

src/components/Countrt.jsx
const counter = () => (
    <Spring
        from={{ number: 0 }}
        to={{ number: 10 }}
        delay= '1000'>
        {props => <div>{props.number.toFixed()}</div>}
    </Spring>
)

The counter now starts after the page animations complete. You can also add this delay through the config prop, which will be covered when discussing the Spring configurations.

Step 4 — Adjusting Spring config

As mentioned before, Springs are physics based. This means you don’t have to manually deal with durations and curves. This is helpful as it takes away some of the heavy math you may have to cover. However, you can still adjust the behavior of our Spring by tweaking its tension, friction, delay, mass, and other behaviors through the config property.

react-spring includes presets that you can use to tweak your Springs. To use them you must import config from the react-spring package and feed them to the config property of the Spring. To prevent any confusion around which config is which, take a look at this example:

import React from 'react';
import { Spring, config } from'react-spring';

const counter = () => (
    <Spring
        from={{ number: 0 }}
        to={{ number: 10 }}
        delay= '1000'
        config = { config.molasses }>
        {props => <div>{props.number.toFixed()}</div>}
    </Spring>
)

export default counter;

In the example above, you used the molasses preset. This is a high tension and friction preset provided by react-spring. The presets typically define the tension and friction properties of out Spring. These presets include molasses, default, slow, stiff and wobbly.

While the presets only define the tension and friction, you can manually configure other properties of the Spring animation. A few examples include delay, mass, velocity, and duration. For a full list of properties you can configure, along with other options that can be passed as props, check out this page.

Step 5 — Exploring Usage with Hooks

The React team recently introduced React Hooks. React Hooks allows you to create functional components that can permanently store data and cause effects, which adds state to functional components. At the time of this writing, hooks are only available in React 16.7 alpha. To use hooks you will need to upgrade to the 16.7 alpha versions of react and react-dom.

To do this, run the following commands:

  1. yarn remove react-dom && yarn add react-dom@16.7.0-alpha.0
  1. yarn remove react && yarn add react@16.7.0-alpha.0

We can use hooks out of the box with react-spring, which exports a hook called useSpring. This hook allows you to define and update data and will generally consist of the same values you would pass as props. useSpring will turn it into animated data. To showcase this, let’s look at how we can have more text rendered after our previous animations complete.

Create a new component file called Hooks.jsx and add the following code:

Hooks.jsx
import React from 'react';
import { useSpring, animated } from 'react-spring';

const HookedComponent = () => {
    const [props] = useSpring({
        opacity: 1,
        color: 'white',
        from: { opacity: 0 },
        delay: '2000'
    })
    return <animated.div style={props}>This text Faded in Using hooks</animated.div>
}

export default HookedComponent;

This code passes the spring settings as an object of arguments to useSpring. It will then pass these values to the animated element that creates the animated spring. The delay is set to 2000 milliseconds to ensure the text from the hooked component fades in after the counter is finished.

Now let’s import this into App.js and use the HookedComponent in our app. After cleaning up some of the initial boilerplate code from create-react-app. Fire up your final application to review the changes.

Final project with text explaining each animation's behavior

Conclusion

You have now set up a trial application with react-spring. Spring provides effective means of animating React applications while taking away a large amount of the workload from the developer.

You can build on Spring by using react-spring’s other components. Overall, react-spring is includes a variety of options depending on your animation needs.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Austin Roy

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel