Creating Dynamic Animations with the React-Motion Library
Written on
Introduction to React-Motion
The react-motion library simplifies the process of adding animations to your React applications. In this guide, we’ll explore the basics of getting started with the TransitionMotion component.
Integrating TransitionMotion for Animations
To animate components when they mount or unmount, we can utilize the TransitionMotion component. Here’s a sample implementation:
import React, { useEffect, useState } from "react";
import { spring, TransitionMotion } from "react-motion";
export default function App() {
const [items, setItems] = useState([
{ key: "a", size: 10 },
{ key: "b", size: 20 },
{ key: "c", size: 30 }
]);
const willLeave = () => {
return { width: spring(0), height: spring(0) };};
useEffect(() => {
setItems([
{ key: "a", size: 10 },
{ key: "b", size: 20 }
]);
}, []);
return (
<>
<TransitionMotion
willLeave={willLeave}
styles={items.map((item) => ({
key: item.key,
style: { width: item.size, height: item.size }
}))}
>
{(interpolatedStyles) => (
<div>
{interpolatedStyles.map((config) => {
return (
<div
key={config.key}
style={{ ...config.style, border: "1px solid" }}
/>
);
})}
</div>
)}
</TransitionMotion>
</>
);
}
In this code, we implement the TransitionMotion to create a transition effect, particularly visible when a component is removed. The willLeave function specifies the animation that occurs during the exit phase.
Adjusting Animation Parameters
The styles prop is essential as it defines the styles for each animated item, with a unique key necessary for identification during animation. We can animate both width and height properties.
To modify the characteristics of the spring animation, such as stiffness and damping, we can provide a second argument:
const willLeave = () => {
return {
width: spring(0, { stiffness: 120, damping: 17 }),
height: spring(0, { stiffness: 120, damping: 17 })
};
};
In this example, we adjust the animation's behavior by tweaking the stiffness and damping values. Additionally, we can introduce a precision property to control the rounding of the interpolated values and the speed of the animation.
Conclusion
In summary, utilizing the TransitionMotion component allows us to create seamless transition effects within our React components, enhancing user experience through dynamic animations.