Skip to main content

(II) Shrink Expand

What we're gonna be building

Code

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

const ShrinkGrow = () => {
const [animate, setAnimate] = useState(true);

const { scale } = useSpring({
from: { scale: animate ? 0 : 1 },
to: { scale: animate ? 1 : 0 },
});

useEffect(() => {
const timeout = setTimeout(() => {
setAnimate(!animate);
}, 1000);
return () => {
clearTimeout(timeout);
};
}, [animate]);

return (
<animated.div
style={{
width: 80,
background: "#ff6",
height: 80,
borderRadius: 8,
scale,
}}
/>
);
};

Code Breakdown

As with Recipe 1, our code can be divided into 3 sections

  1. Animation definition

const [animate, setAnimate] = useState(false);

const { scale } = useSpring({
from: { scale: animate ? 0 : 1 },
to: { translation: animate ? 1 : 0 },
});
  • The controller follows the same logic as Recipe 1, except, we replace transition with scale,
    and let our value range between 0 and 1. know more here
  1. Animation control

useEffect(() => {
const timeout = setTimeout(() => {
setAnimate(!animate);
}, 1000);
return () => {
clearTimeout(timeout);
};
}, [animate]);
  • You must be starting to see a trend here, our animation controller looks very similar,
    to Recipe 1 Animation Control, this is because it is performing the same action, except on a different style property of the element.
  1. component declaration

<animated.div
style={{
width: 80,
background: "#ff6",
height: 80,
borderRadius: 8,
scale,
}}
/>
  • like Recipe 1 component declaration, we declare our component, and apply a different style property, scale onto it.
    Thus allowing for our component to Shrink and Grow!

Conclusion

I hope that helps understand a variation, to apply react-spring based value as style property to create an animated component. Since this tutorial was very similar to Recipe 1, I have added links to the similar sections for help. If you're clear with these, lets move on to making these components more reusable, using HOC architecture!