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:
➡️ 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.
➡️ React.js
➡️ Transition in React
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:
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.
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.
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.
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:
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.
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:
<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>
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:
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).
ReactElement
Required function.
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.
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
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.
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.
The team at Mindbowser was highly professional, patient, and collaborative throughout our engagement. They struck the right balance between offering guidance and taking direction, which made the development process smooth. Although our project wasn’t related to healthcare, we clearly benefited...
Founder, Texas Ranch Security
Mindbowser played a crucial role in helping us bring everything together into a unified, cohesive product. Their commitment to industry-standard coding practices made an enormous difference, allowing developers to seamlessly transition in and out of the project without any confusion....
CEO, MarketsAI
I'm thrilled to be partnering with Mindbowser on our journey with TravelRite. The collaboration has been exceptional, and I’m truly grateful for the dedication and expertise the team has brought to the development process. Their commitment to our mission is...
Founder & CEO, TravelRite
The Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork