Categories
React

Add Animation to Our React App with the react-spring Library

Spread the love

With the react-spring library, we can render animations in our React app easily.

In this article, we’ll take a look at how to get started with react-spring.

Installation

We can install the react-spring package by running:

npm install react-spring

Basic Animation

We can create basic animations with the useSpring hook.

For example, we can write:

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

export default function App() {
  const props = useSpring({ opacity: 1, from: { opacity: 0 } });
  return <animated.div style={props}>hello world</animated.div>;
}

We call the useSpring hook to set the opacity that’s applied after the animation is done.

The from property has the styles before the animation.

The animated.div component lets us create a div that can be animated.

We pass in the props variable to the style prop to style it.

We can also animate text:

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

export default function App() {
  const props = useSpring({ number: 1, from: { number: 0 } });
  return <animated.span>{props.number}</animated.span>;
}

We animate props.number when it changes from 0 to 1.

Also, we can scroll a div with the scroll property.

For example, we can write:

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

export default function App() {
  const props = useSpring({ scroll: 300, from: { scroll: 0 } });
  return (
    <animated.div
      scrollTop={props.scroll}
      style={{ overflowY: "scroll", height: 200 }}
    >
      {Array(100)
        .fill()
        .map((_, i) => (
          <p key={i}>{i}</p>
        ))}
    </animated.div>
  );
}

We scroll 300px down from the top.

Also, we can combine multiple effects together:

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

export default function App() {
  const { o, xyz, color } = useSpring({
    from: { o: 0, xyz: [0, 0, 0], color: "red" },
    o: 1,
    xyz: [10, 20, 5],
    color: "green"
  });

  return (
    <animated.div
      style={{
        color,
        background: o.interpolate((o) => `rgba(210, 57, 77, ${o})`),
        transform: xyz.interpolate(
          (x, y, z) => `translate3d(${x}px, ${y}px, ${z}px)`
        ),
        border: interpolate([o, color], (o, c) => `${o * 10}px solid ${c}`),
        padding: o
          .interpolate({ range: [0, 0.5, 1], output: [0, 0, 10] })
          .interpolate((o) => `${o}%`),
        borderColor: o.interpolate({
          range: [0, 1],
          output: ["red", "#ffaabb"]
        }),
        opacity: o.interpolate([0.1, 0.2, 0.6, 1], [1, 0.1, 0.5, 1])
      }}
    >
      {o.interpolate((n) => n.toFixed(2))}
    </animated.div>
  );
}

We call the useSpring hook to generate some values that are passed into the style prop.

We interpolate o , x , y , and z into various values to change the style of the div as it is animating.

We can pass in values that are created from the react-spring hooks into components directly.

For instance, we can write:

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

export default function App() {
  const [state, setState] = useState(1);
  const props = useSpring({ x: state ? 1 : 0 });
  return (
    <>
      <button onClick={() => setState((state) => (state === 1 ? 0 : 1))}>
        toggle
      </button>
      <animated.div
        style={{
          transform: props.x
            .interpolate({
              range: [0, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 1],
              output: [1, 0.97, 0.9, 1.1, 0.9, 1.1, 1.03, 1]
            })
            .interpolate((x) => `scale(${x})`),
          backgroundColor: "red",
          height: 100,
          width: 100
        }}
      />
    </>
  );
}

We add the div and then we can change the scale as we click the toggle button by setting the transform prop.

We map the value from the range to the output .

And x is the value of output that corresponds to the one in range .

Conclusion

We can add basic animation to our React app with react-spring.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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