Categories
React

Animate with the react-spring Library — useChain and Spring Component

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.

useChain

The useChain hook lets us render one transition after the other.

For example, we can write:

import React, { useRef, useState } from "react";
import {
  useTransition,
  animated,
  useChain,
  useSpring,
  useTrail
} from "react-spring";

export default function App() {
  const [on, toggle] = useState(false);

  const springRef = useRef();
  const spring = useSpring({
    ref: springRef,
    from: { opacity: 0.5 },
    to: { opacity: on ? 1 : 0.5 },
    config: { tension: 250 }
  });

  const trailRef = useRef();
  const trail = useTrail(5, {
    ref: trailRef,
    from: { fontSize: "10px" },
    to: { fontSize: on ? "35px" : "10px" }
  });

  useChain(on ? [springRef, trailRef] : [trailRef, springRef]);

  return (
    <div>
      {trail.map((animation, index) => (
        <animated.div style={{ ...animation, ...spring }} key={index}>
          Hello World
        </animated.div>
      ))}

      <button onClick={() => toggle(!on)}>toggle</button>
    </div>
  );
}

to animate the toggling of the size of the ‘Hello World’ text.

We create the on state with the toggle function to toggle the on state.

Then we create a ref with the useRef hook and create a transition with the useSpring hook.

We set the ref property to the springRef so we can use that in the useChain hook.

Likewise, we use the useTrail to create the 2nd transition.

Then we use th useChain hook to create the 2 animations combined together.

Their order depends on the value of the on state.

Then we render the Hello World text by calling the trail.map method to apply the styles for each stage of the animation.

Now when we click ‘toggle’, we see the Hello World text size change.

Render Props API

The react-spring library comes with a render props API.

To use this to create animations, we use the Spring component.

For example, we can write:

import React from "react";
import { Spring } from "react-spring/renderprops";

export default function App() {
  return (
    <div>
      <Spring from={{ opacity: 0 }} to={{ opacity: 1 }}>
        {(props) => <div style={props}>hello</div>}
      </Spring>
    </div>
  );
}

to add the Spring component.

We set the from prop to add the styles to apply at the start of the animation.

And we add the to prop to add the styles to apply at the end of the animation.

And in the render prop, we pass in a function with the content that we want to render.

The props parameter has the styles that are applied at each stage of the animation, so we pass that into the style prop to apply them.

Also, we can animate numbers by writing:

import React from "react";
import { Spring } from "react-spring/renderprops";

export default function App() {
  return (
    <div>
      <Spring from={{ number: 0 }} to={{ number: 1 }}>
        {(props) => <div>{props.number}</div>}
      </Spring>
    </div>
  );
}

We set the number to display at the beginning and the end of the animation with the from and to props respectively.

Then we the number animate from 0 to 1.

Conclusion

We can use the useChain hook to chain animations.

And we can use the Spring component to render animations.

Categories
React

Animate with the react-spring Library — useTransition Hook

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.

useTransition

We can use the useTransition hook to add transitions to our React components.

For example, we can write:

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

const arr = [
  { text: 1, key: 1 },
  { text: 2, key: 2 },
  { text: 3, key: 3 }
];

export default function App() {
  const [items] = useState(arr);
  const transitions = useTransition(items, (item) => item.key, {
    from: { transform: "translate3d(0,-40px,0)" },
    enter: { transform: "translate3d(0,0px,0)" },
    leave: { transform: "translate3d(0,-40px,0)" }
  });
  return transitions.map(({ item, props, key }) => (
    <animated.div key={key} style={props}>
      {item.text}
    </animated.div>
  ));
}

to animate the rendering of the arr array with the useTransition hook.

We create the items state from the useState hook.

Then we pass that into the useTransition hook as its first argument.

In the 2nd argument, we pass in a function to return the key property of each item, which is its unique ID.

It’s used by React to keep track of the items.

The 3rd argument has an object with the styles that we want to render before the animation with the from property.

The enter property has the styles to display when the item enters.

And the leave property has the styles to display when the item leaves.

Now we should see the numbers move down to the screen.

We can also use the useTransition hook to toggle between components.

For example, we can write:

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

export default function App() {
  const [toggle, set] = useState(false);
  const transitions = useTransition(toggle, null, {
    from: { position: "absolute", opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 }
  });
  return (
    <>
      <button onClick={() => set(!toggle)}>toggle</button>
      {transitions.map(({ item, key, props }) =>
        item ? (
          <animated.div style={props} key={key}>
            <span role="img" aria-label="smile">
              ?
            </span>
          </animated.div>
        ) : (
          <animated.div style={props} key={key}>
            <span role="img" aria-label="smile">
              ?
            </span>
          </animated.div>
        )
      )}
    </>
  );
}

We have the toggle state, which is toggled with the button.

Then we call the useTransition hook to apply the styles by passing in the toggle state as the first argument.

The 3rd argument has the styles we want to apply when we animate.

When item toggles between truthy and falsy, then the corresp[onding emoji will display since we call transitions.map to map the transitions and.

item has the value that toggle has.

We can also use it to render things that are displayed when a condition is true .

For instance, we can write:

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

export default function App() {
  const [show, set] = useState(false);
  const transitions = useTransition(show, null, {
    from: { position: "absolute", opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 }
  });
  return (
    <>
      <button onClick={() => set(!show)}>toggle</button>
      {transitions.map(
        ({ item, key, props }) =>
          item && (
            <animated.div key={key} style={props}>
              <span role="img" aria-label="smile">
                ✌️
              </span>
            </animated.div>
          )
      )}
    </>
  );
}

Then when item is true , which is true when show is true , the emoji is displayed.

Conclusion

We can add transitions to our React components easily with the useTransition hook.

Categories
React

Animate with the react-spring Library — useSprings and useTrail Hooks

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.

useSprings

The useSprings hook lets us create multiple springs each with its own config.

For example, we can write:

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

const items = [
  { text: "foo", opacity: 0.3, id: 1 },
  { text: "bar", opacity: 0.6, id: 2 },
  { text: "baz", opacity: 0.9, id: 3 }
];

export default function App() {
  const springs = useSprings(
    items.length,
    items.map((item) => ({ opacity: item.opacity, from: { opacity: 0 } }))
  );

  return (
    <>
      {springs.map((props, i) => (
        <animated.div style={props} key={i}>
          {items[i].text}
        </animated.div>
      ))}
    </>
  );
}

to create the animation styles for each item with the useSprings hook.

The first argument is the number of style objects to create.

The 2nd argument is an array with the styles we want to apply.

Then in the JSX, we apply the styles by passing in the props to the style prop.

We can also control our animation with the set and stop functions.

For example, we can write:

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

const items = [
  { text: "foo", opacity: 0.3, id: 1 },
  { text: "bar", opacity: 0.6, id: 2 },
  { text: "baz", opacity: 0.9, id: 3 }
];

export default function App() {
  const [springs, set, stop] = useSprings(items.length, (index) => ({
    opacity: items[index].opacity,
    from: { opacity: 0 }
  }));

  return (
    <>
      <button onClick={() => set((index) => ({ opacity: 1 }))}>start</button>
      <button onClick={() => stop()}>stop</button>
      {springs.map((props, i) => (
        <animated.div style={props} key={i}>
          {items[i].text}
        </animated.div>
      ))}
    </>
  );
}

We have the same items array.

And we use the useSpring hook with a function as the 2nd argument instead of an array of styles.

Calling it with a function as the 2nd argument will give us the set and stop functions in addition to springs ,

The set function lets us run the animation with the given style.

And the stop function lets us stop the animation.

Then we display the animated divs the same way.

useTrail

The useTrail lets us create multiple springs with a single config.

For example, we can write:

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

const items = [
  { text: "foo", id: 1 },
  { text: "bar", id: 2 },
  { text: "baz", id: 3 }
];

export default function App() {
  const trail = useTrail(items.length, { opacity: 1, from: { opacity: 0 } });

  return (
    <>
      {trail.map((props, i) => (
        <animated.div style={props} key={i}>
          {items[i].text}
        </animated.div>
      ))}
    </>
  );
}

The first argument is the number of animation style objects to create.

And the 2nd argument is the animation style to create.

Then we can apply them as we do with the useSprings hook.

Conclusion

We can create animations for a group of components with the useSprings and useTrail hooks.

Categories
React

Animate with the react-spring Library — useSpring Hook

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.

useSpring

We can use the useSpring hook to add our animation.

For example, we can write:

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

export default function App() {
  const [props, set, stop] = useSpring(() => ({ opacity: 1 }));
  const [toggle, setToggle] = useState();

  useEffect(() => {
    set({ opacity: toggle ? 1 : 0 });
  }, [toggle]);

  return (
    <>
      <button onClick={() => setToggle(!toggle)}>start</button>
      <button onClick={() => stop()}>stop</button>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

We pass in callback into the useSpring hook to create our animation.

We also have the toggle state to let us toggle the opacity with the set function.

So when we click start, we’ll see the fading of the text toggled.

And we have the stop function to stop the animation.

We can also use the useSpring by passing in an object.

For example, we can write:

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

export default function App() {
  const props = useSpring({
    from: { opacity: 0 },
    to: { opacity: 1, color: "red" }
  });

  return (
    <>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

We animate from the styles with the from property to the styles in the to property.

We can shorten this to:

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

export default function App() {
  const props = useSpring({
    from: { opacity: 0 },
    opacity: 1,
    color: "red"
  });

  return (
    <>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

Async Chains and Scripts

We can animate asynchronously with the next function.

For instance, we can write:

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

export default function App() {
  const props = useSpring({
    to: async (next, cancel) => {
      await next({ opacity: 1, color: "#ffaaee" });
      await next({ opacity: 0, color: "rgb(14,26,19)" });
    },
    from: { opacity: 0, color: "red" }
  });

  return (
    <>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

The to method is an async function that has the next and cancel functions as parameters.

next lets us set the styles we want to apply in our animation.

And cancel lets us cancel the animation.

from is still an object with the initial styles of our div.

Also, we can create the to property with an array by writing:

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

export default function App() {
  const props = useSpring({
    to: [
      { opacity: 1, color: "#ffaaee" },
      { opacity: 0, color: "rgb(14,26,19)" }
    ],
    from: { opacity: 0, color: "red" }
  });

  return (
    <>
      <animated.div style={props}>i will fade</animated.div>
    </>
  );
}

The array has objects with the styles we want to apply.

Conclusion

The useSpring hook lets us create animations easy for a single element.

Categories
React

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

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.