Categories
React

Animate with the react-spring Library — Keyframes

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.

Animate Mounting or Unmounting Components

We can animate mounting or unmounting components.

For example, we can write:

import React, { useState } from "react";
import { Transition } from "react-spring/renderprops";

export default function App() {
  const [show, set] = useState(false);

  return (
    <div>
      <button onClick={() => set(!show)}>toggle</button>
      <Transition
        items={show}
        from={{ opacity: 0 }}
        enter={{ opacity: 1 }}
        leave={{ opacity: 0 }}
      >
        {(show) =>
          show &&
          ((props) => (
            <div style={props}>
              <span role="img" aria-label="smile">
                ✌
              </span>
              ️
            </div>
          ))
        }
      </Transition>
    </div>
  );
}

to show the emoji when the show state is true .

We get the show state from the Transition component’s items prop.

The from , enter , and leave props have the styles to show when the animation starts, when the item enters the screen, and when it leaves the screen respectively.

The props parameter has the styles that we’re rendering during animation.

Keyframes

The Keyframes component lets us chain, compose, and orchestrate animations.

For example, we can write:

import React from "react";
import { config, Keyframes } from "react-spring/renderprops";

const delay = (ms) => new Promise((resolve) => resolve, ms);

const Container = Keyframes.Spring({
  show: { opacity: 1 },
  showAndHide: [{ color: "green" }, { color: "red" }],
  wiggle: async (next, cancel, ownProps) => {
    await next({ x: 100, config: config.wobbly });
    await delay(1000);
    await next({ x: 0, config: config.gentle });
  }
});

export default function App() {
  return (
    <div>
      <Container state="showAndHide">
        {(styles) => <div style={styles}>Hello</div>}
      </Container>
    </div>
  );
}

Then we animate our text from green to red since we have the showAndHide property with an array of styles for the start and end of the animation respectively.

We use the Container component, which is created from the Keyframes.Spring function.

The state is set to the property name with the keyframes that we want to animate.

We can also specify one keyframe with an object, or an async function with the next , cancel , and ownProps parameters.

next is called with the animation config and styles to apply.

We can also pass in a function to Keyframes.Spring to create the animation.

For instance, we can write:

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

const Script = Keyframes.Spring(async (next) => {
  while (true) {
    await next({ color: "red", from: { color: "green" }, reset: true });
  }
});

export default function App() {
  return (
    <div>
      <Script>{(styles) => <div style={styles}>Hello</div>}</Script>
    </div>
  );
}

We pass the callback into Keyframes.Spring that calls next to toggles color between red and green.

Also, we can pass in an array into Keyframes.Spring to add the keyframes by writing:

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

const Chain = Keyframes.Spring([{ color: "red" }, { color: "green" }]);

export default function App() {
  return (
    <div>
      <Chain>{(styles) => <div style={styles}>Hello</div>}</Chain>
    </div>
  );
}

Conclusion

We can add keyframes to our animations with react-spring’s Keyframes.Spring function.

Categories
React

Animate with the react-spring Library — Trail and Transition Components

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.

Trail

The Trail component is used to animate the first item of a list of elements.

The rest form a natural trail and follow the previous sibling.

For example, we can write:

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

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

export default function App() {
  return (
    <div>
      <Trail
        items={items}
        keys={(item) => item.key}
        from={{ transform: "translate3d(0,-40px,0)" }}
        to={{ transform: "translate3d(0,0px,0)" }}
      >
        {(item) => (props) => <div style={props}>{item.text}</div>}
      </Trail>
    </div>
  );
}

We use the Trail component with the items prop to.

It takes an array of data we want to render.

keys takes a function which returns the key value.

from takes an object that lets us apply the styles at the start of the animation.

to has an object that lets us apply the styles at the end of the animation.

The render prop is a function that takes the item parameter and returns a function that takes the props parameter and returns the JSX to render.

props has the style that is applied during the animation.

Now we should see the numbers slide down to the page when we mount the component.

Transition

The Transition component animates the component lifecycles as the component mounts, unmounts, or changes.

For example, we can use it by writing:

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

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

export default function App() {
  return (
    <div>
      <Transition
        items={items}
        keys={(item) => item.key}
        from={{ transform: "translate3d(0,-40px,0)" }}
        enter={{ transform: "translate3d(0,0px,0)" }}
        leave={{ transform: "translate3d(0,-40px,0)" }}
      >
        {(item) => (props) => <div style={props}>{item.text}</div>}
      </Transition>
    </div>
  );
}

We have the Transition component that takes the items with the items to render.

keys has a function to return the unique key from the object.

from has the styles when we start the animation.

enter has the styles when the items enter the screen.

And leave has the styles when the items leave the screen.

Now we should see the number slide down the screen.

We can also use it to animate toggling between components.

For instance, we can write:

import React, { useState } from "react";
import { Transition } from "react-spring/renderprops";

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

return (
    <div>
      <button onClick={() => set(!toggle)}>toggle</button>
      <Transition
        items={toggle}
        from={{ position: "absolute", opacity: 0 }}
        enter={{ opacity: 1 }}
        leave={{ opacity: 0 }}
      >
        {(toggle) =>
          toggle
            ? (props) => (
                <div style={props}>
                  <span role="img" aria-label="smile">
                    ?
                  </span>
                </div>
              )
            : (props) => (
                <div style={props}>
                  <span role="img" aria-label="smile">
                    ?
                  </span>
                </div>
              )
        }
      </Transition>
    </div>
  );
}

We have the useState hook to create the toggle state.

We toggle that with the toggle button.

In the Transition component, we get the value of the toggle state.

Then we use that value to render the emoticon we want.

The enter and leave styles are set in the enter and leave props.

Conclusion

We can use the Trail component to render animation of multiple the first item with the rest following it.

The Transition component lets us render the component lifecycle.

Categories
React

Animate with the react-spring Library — Customize 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.

Spring Component and Interpolation

We can use the Spring component to interpolate anything.

For example, we can write:

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

export default function App() {
  return (
    <div>
      <Spring
        from={{
          width: 100,
          padding: 0,
          background: "linear-gradient(to right, #30e8bf, #ff8235)",
          transform: "translate3d(400px,0,0) scale(2) rotateX(90deg)",
          boxShadow: "0px 100px 150px -10px #2D3747",
          borderBottom: "0px solid white",
          shape: "M20,380 L380,380 L380,380 L200,20 L20,380 Z",
          textShadow: "0px 5px 0px white"
        }}
        to={{
          width: "auto",
          padding: 20,
          background: "linear-gradient(to right, #009fff, #ec2f4b)",
          transform: "translate3d(0px,0,0) scale(1) rotateX(0deg)",
          boxShadow: "0px 10px 20px 0px rgba(0,0,0,0.4)",
          borderBottom: "10px solid #2D3747",
          shape: "M20,20 L20,380 L380,380 L380,20 L20,20 Z",
          textShadow: "0px 5px 15px rgba(255,255,255,0.5)"
        }}
      >
        {(props) => <div style={props}></div>}
      </Spring>
    </div>
  );
}

We have the from prop with the initial styles that we apply to the render props function’s div.

We also have the to prop with the styles that are applied when the animation is done.

props has the styles that are computed during the animation.

And we apply them by passing them into the style prop.

Spring Component Config

We can configure the Spring component with some preset values.

They include:

  • config.default — { tension: 170, friction: 26 }
  • config.gentle — { tension: 120, friction: 14 }
  • config.wobbly — { tension: 180, friction: 12 }
  • config.stiff — { tension: 210, friction: 20 }
  • config.slow — { tension: 280, friction: 60 }
  • config.molasses — { tension: 280, friction: 120 }

For example, we can write:

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

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

to set the configuration with the config prop.

The following properties can be configured:

  • mass — spring-mass, defaults to 1
  • tension —spring energetic load, default value 170
  • friction — spring resistance, default value 26
  • clamp — when true, stops the spring once it overshoots its boundaries, defaults to false
  • precision —precision, defaults to 0.01
  • velocity — initial velocity, defaults to 0
  • delay — delay, defaults to 0
  • duration — if > than 0 will switch to a duration-based animation instead of spring physics, defaults to undefined
  • easing —linear by default, you can use any easing you want, defaults value is t => t

We can configure it with our own object:

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

export default function App() {
  return (
    <div>
      <Spring
        config={{ tension: 0, friction: 2, precision: 0.1 }}
        from={{ opacity: 0 }}
        to={{ opacity: 1 }}
      >
        {(props) => <div style={props}>hello</div>}
      </Spring>
    </div>
  );
}

And we can configure it with our own function:

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

export default function App() {
  return (
    <div>
      <Spring
        to={{ opacity: 1, width: 100, backgroundColor: "red" }}
        config={(key) => (key === "width" ? config.slow : config.wobbly)}
        from={{ opacity: 0, width: 0, backgroundColor: "red" }}
      >
        {(props) => <div style={props}>hello</div>}
      </Spring>
    </div>
  );
}

We get the key from the styles and return the config based on that.

Conclusion

We can use the Spring component with various styles and config to customize our animation.

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.