Seamless Moves: Mastering Transitions with React Motion

Introduction

Transitions are widely used in projects, but as a front-end developer you write lines of code for handling smooth transitions you need to care about the curve, and timing while in transition.

This blog will cover how to use the React-Motion transition library to solve some physics issues like damping and stiffness.

React Motion was developed by Cheng Lou, an engineer at Facebook, and was initially released in 2014. Since then, it has become one of the most widely used libraries for creating animations in React applications.

The library provides a set of physics-based animation components that make it easy to create smooth, natural-looking transitions between different states of your application. These components include:

components of react motion library

➡️ Motion: A component that animates a set of values from one state to another using spring physics.
➡️ StaggeredMotion: A component that animates a set of values from one state to another using spring physics, but with a staggered delay between each value.
➡️ TransitionMotion: A component that animates the addition, removal, and reordering of elements in a list using spring physics.

Prerequisites

➡️ React.js

➡️ Transition in React

Overview

React Motion is a popular open-source library for adding animated transitions to React applications. It is built on top of React’s render function and uses the React component lifecycle to create smooth animations that respond to user interactions.

In addition to these components, React Motion also provides a set of helper functions for working with animations, such as interpolate, which maps one range of values to another range, and spring, which creates a spring physics configuration.

One of the key benefits of React Motion is that it provides a simple and declarative API for creating animations. Instead of manually defining animation frames and timing functions, you can simply specify the start and end states of your animation, along with any desired physics-based properties like stiffness and damping.

Here’s an example of how you might use React Motion to create a simple animation:

import "./signIn.css";
import React from 'react';
import { spring, Motion } from 'react-motion';


const App = () => {


return (
<div>
<div className="signin-contianer">
<Motion defaultStyle={{
opacity: 0,
marginLeft: -2000,
padding: 0
}} style={{
opacity: spring(1),
marginLeft: spring(100, { stiffness: 90, damping: 20 }),
}}>
{value =>
<div style={{
transform: `translateX(${value.marginLeft}px)`,
}}
className="div-container">
<div style={{
backgroundColor: "aqua",
}} >
A
</div>
<div style={{
backgroundColor: "aqua"
}} >
B
</div>
<div style={{
backgroundColor: "aqua"
}} >
C
</div>
</div>
}
</Motion>
</div>
</div>
)
}


export default App;

In this example with the help of the <Motion></Motion> component default style has been set, default opacity : 0 margin-left: -2000 and then the style has been settled with spring for opacity is 1 and margin-lift has 100.

Overall, React Motion is a powerful and flexible library for adding animations to your React applications. Whether you’re building a simple prototype or a complex production app, React Motion can help you create smooth, natural-looking transitions that enhance the user experience.

Certainly! Here are a few more pieces of information about the React Motion library:

Custom Animation Hooks

React Motion offers a custom hook called useSpring that simplifies the creation of animations. The useSpring hook takes an initial state and returns an animated state value and a function to update the state.

Performance Optimization

React Motion provides a few performance optimization techniques to ensure that animations run smoothly, even on slower devices. One technique is called “batching,” which groups multiple animation updates together and performs them in a single render cycle. This helps to reduce the number of DOM updates and increase overall performance.

Another optimization technique is called “shouldComponentUpdate,” which prevents unnecessary updates to the animation components. By default, React Motion components will update on every render cycle, even if the animation values haven’t changed. However, you can use the shouldComponentUpdate lifecycle method to control when the component should update.

Extensible Animations

React Motion provides a range of built-in physics-based animations, but it’s also possible to create custom animations using the spring function. The spring function takes a set of configuration options, such as stiffness, damping, and mass, and returns an animation function that can be used to animate any value. Here’s an example:

import React, {useState} from 'react';
import { spring } from 'react-motion';


const SprintPactice = () => {
const [isTogled, setToggled] = useState(false);
const setSpringVal = {
opacity: spring(isTogled ? 1 : 0),
x : spring(isTogled ? 500 : 0)
}


return (
<div onClick={()=> {setToggled(!isTogled)}}>
<div style={{
opacity: setSpringVal.opacity,
transform: `translateX(${setPringVal.x}px)`
}}>
Click me to see the transition !
</div>
</div>
)
}


export default SprintPactice;

In this example, we’re using the spring function to create a custom animation that animates the opacity value from 0 to 1. We’ve set the stiffness and damping values to 100 and 10, respectively, to create a fast, bouncy animation. We then use the animation function to update the opacity value of a div element.

Level Up Your React JS Projects with Our Expert Developers!

Spring: (val: number, config?: SpringHelperConfig)

OpaqueConfig

In React Motion, a “spring” is a physics-based animation function that generates a series of interpolated values over time. The spring function takes a configuration object with several properties, including:

  • Stiffness: A value that controls the “stiffness” of the spring. Higher values will result in faster, more abrupt animations.
  • Damping: A value that controls the “damping” of the spring. Higher values will result in slower, smoother animations.
  • Mass: A value that controls the mass of the animated object. Higher values will result in slower, more deliberate animations.
  • Initial Velocity: A value that controls the initial velocity of the animation.

When the spring function is called, it returns an animation object with two properties: value and velocity. The value property is the current interpolated value of the animation, and the velocity property is the current velocity of the animation.

Presets for {stiffness, damping}

In React Motion, a “preset” is a predefined set of values for the stiffness, damping, and precision properties of the spring function. Presets are designed to make it easier to create common types of animations without having to manually tune the physics parameters.

React Motion includes several built-in presets, including noWobble, gentle, wobbly, and stiff. Here’s a brief overview of each preset:

  • noWobble: This preset produces a very stiff, non-oscillating spring. It’s useful for creating animations that have a sudden, abrupt start and stop.
  • Gentle: This preset produces a soft, smooth spring with a slower start and stop. It’s useful for creating animations that feel more natural and organic.
  • Wobbly: This preset produces a spring that oscillates slightly before settling. It’s useful for creating animations that feel bouncy or elastic.
  • Stiff: This preset produces a very stiff, oscillating spring. It’s useful for creating animations that have a very deliberate, mechanical feel.

Components

Motion

<Motion defaultStyle={{
opacity: 0,
marginLeft: -2000,
padding: 0
}} style={{
opacity: spring(1),
marginLeft: spring(100, { stiffness: 90, damping: 20 }),
}}>
{value =>
<div style={{
transform: `translateX(${value.marginLeft}px)`,
}}
className="div-container">
<div style={{
backgroundColor: "aqua",
}} >
A
</div>
</div>
}
</Motion>

Props

style: Style

Required function.

The Style type is an object that maps to either a number or an OpaqueConfig returned by spring() above. Must keep the same keys throughout the component’s existence. The meaning of the values:

  • an OpaqueConfig returned from spring(x): interpolate to x.
  • a number x: jump to x, do not interpolate.

defaultStyle?: PlainStyle

Optional function.

The PlainStyle type maps to numbers. Defaults to an object with the same keys as the style above, whose values are the initial numbers you’re interpolating on. Note that during subsequent renders, this prop is ignored. The values will interpolate from the current ones to the destination ones (specified by style).

children: (interpolatedStyle: PlainStyle)

ReactElement

Required function.

  • interpolatedStyle: the interpolated style object passed back to you. E.g. if you gave style={{x: spring(10), y: spring(20)}}, you’ll receive as interpolatedStyle, at a certain time, {x: 5.2, y: 12.1}, which you can then apply on your div or something else.
  • Return: must return one React element to render.

Staggered Motion

const StaggeredMotionComponent = () => {
const [xyAxis, setXyAxis] = useState({ x: 250, y: 300 });
const Images = [img1, img2, img3, img4, img5];
useEffect(() => {
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('touchmove', handleMouseLeave);
}, []);
const handleMouseMove = ({ pageX: x, pageY: y }) => {
setXyAxis({ x, y });
};
const handleMouseLeave = ({ touches }) => {
handleMouseMove(touches[0]);
};
const getPrevStyle = (prevStyles) => {
const endValue = prevStyles.map((_, i) => {
return i === 0 ?
xyAxis :
{
y: spring(prevStyles[i - 1].y, presets.wobbly),
x: spring(prevStyles[i - 1].x, presets.wobbly)
}
});
return endValue;
};
return (
<div>
<StaggeredMotion
defaultStyles={range(5).map(() => ({ x: 0, y: 0 }))}
styles={getPrevStyle}>
{balls =>
<div className="demo1">
{balls.map(({ x, y }, i) =>
<div
key={i}
className="chats-heads"
style={{
WebkitTransform: `translate3d(${x}px, ${y}px, 0)`,
transform: `translate3d(${x}px, ${y}px, 0)`,
zIndex: balls.length - i,
backgroundImage: `url(${Images[i]})`
}} />
)}
</div>
}
</StaggeredMotion>
</div>
);
};
export default StaggeredMotionComponent;

StaggeredMotion is a component in the React Motion library that allows for creating staggered animations with a specified delay between the start of each animation. It is particularly useful for creating sequential animations in a list or grid.

When using StaggeredMotion, you provide an initial array of values and a function that takes these values and returns an array of styles for each value. The StaggeredMotion component then animates these values from their initial state to their final state. The delay between each animation can be specified using the staggerDuration prop.

StaggeredMotion is a component provided by the React Motion library, which is a popular library for creating fluid, animated UI transitions in React applications.

  • It’s a higher-level component: StaggeredMotion is a higher-level component compared to some of the other components in React Motion, such as Motion and TransitionMotion. This means that it abstracts away some of the details of creating animations, making it easier to use for certain types of animations.
  • It creates staggered animations: As the name suggests, StaggeredMotion is designed to create staggered animations, where each item in a list or grid is animated in sequence with a specified delay between each item.
  • It works with spring animations: StaggeredMotion uses the spring animation system provided by React Motion to animate values. This means that you can create smooth, natural-looking animations that respond to user interactions or changes in data.
  • It requires a getStyles function: To use StaggeredMotion, you need to provide a getStyles function that takes an array of previous styles (or initial styles, if it’s the first call) and returns an array of next styles. This function is called on each frame of the animation, and it’s responsible for calculating the next set of styles for each item in the list.
  • It supports the use of the staggerDuration prop: The staggerDuration prop is an optional prop that can be passed to StaggeredMotion to specify the delay between each item in the list. This can be useful for creating smooth, staggered animations.

Overall, StaggeredMotion is a powerful and flexible component that can be used to create a wide range of staggered animations in React applications. It’s particularly useful for creating animations in lists or grids, where you want to animate each item in the sequence.

Related read: Best Practices for Optimized State Management in React Applications

Transition Motion

TransitionMotion is a component provided by the React Motion library that allows for animating components between multiple states. It is particularly useful for creating complex animations that involve multiple elements or components.

When using TransitionMotion, you provide an array of values, where each value represents a different state of the animation. For each value, you also provide a key and a function that takes the value and returns a style object that describes how the component should be styled in that state.

TransitionMotion then animates the transition between these states, interpolating the style objects to create a smooth, natural-looking animation.
Here’s an example,

import React from 'react';
import { TransitionMotion, spring } from 'react-motion';
const TransitionMotionPractice = () => {
const items = [
{ key: 'a', color: 'red', width: 100 },
{ key: 'b', color: 'green', width: 200 },
{ key: 'c', color: 'blue', width: 150 },
];


function getStyles(prevStyles) {
return items.map(item => {
return {
key: item.key,
style: {
color: item.color,
width: spring(item.width),
},
};
});
}


return (
<div>
<TransitionMotion
defaultStyles={items.map(item => ({ key: item.key, style: item }))}
styles={getStyles}
>
{interpolatedStyles => (
<div>
{interpolatedStyles.map(config => (
<div key={config.key} style={config.style}>
{config.key}
</div>
))}
</div>
)}
</TransitionMotion>
</div>
);
}
export default TransitionMotionPractice;

In this example, we’re animating a set of div elements between three different states, each with a different color and width. The getStyles function maps over each item and returns a style object for each one, using the spring function from React Motion to animate the width property.

The defaultStyles prop provides the initial styles for each item, while the styles prop specifies the next set of styles that the component should transition to.

The interpolatedStyles array returned by TransitionMotion is used to render each item, with its interpolated styles applied as inline styles. The key prop is used to ensure that React can track each item as it animates between states.

Overall, TransitionMotion is a powerful and flexible component that can be used to create complex, multi-state animations in React applications.

coma

Conclusion

One of the key benefits of React Motion is that it uses a physics-based approach to animation, which allows for more natural and lifelike motion. It also provides a flexible API that allows developers to customize the behaviour and appearance of their animations in many different ways.

Overall, React Motion is a great choice for developers looking to create dynamic, engaging user interfaces with smooth and responsive animations. Whether you’re building a small web app or a large enterprise application, React Motion can help you create beautiful, effective animations that enhance the user experience and bring your application to life.

Keep Reading

Keep Reading

Leave your competitors behind! Become an EPIC integration pro, and boost your team's efficiency.

Register Here
  • Service
  • Career
  • Let's create something together!

  • We’re looking for the best. Are you in?