What is react-spring?
react-spring is a spring-physics-based animation library for React applications. It allows developers to create fluid and natural animations with ease, leveraging the power of physics to create realistic motion. The library is highly flexible and can be used for a variety of animation needs, from simple transitions to complex interactive animations.
What are react-spring's main functionalities?
Basic Animations
This feature allows you to create basic animations such as fading in and out. The `useSpring` hook is used to define the animation properties, and the `animated` component is used to apply these properties to a React element.
```jsx
import React from 'react';
import { useSpring, animated } from 'react-spring';
function BasicAnimation() {
const props = useSpring({
to: { opacity: 1 },
from: { opacity: 0 },
});
return <animated.div style={props}>I will fade in</animated.div>;
}
export default BasicAnimation;
```
Keyframe Animations
This feature allows you to create keyframe animations, where an element transitions through multiple states. The `to` property can be an async function that defines a sequence of animations.
```jsx
import React from 'react';
import { useSpring, animated } from 'react-spring';
function KeyframeAnimation() {
const props = useSpring({
from: { transform: 'translate3d(0,0,0)' },
to: async (next) => {
await next({ transform: 'translate3d(100px,0,0)' });
await next({ transform: 'translate3d(0,0,0)' });
},
});
return <animated.div style={props}>I will move</animated.div>;
}
export default KeyframeAnimation;
```
Gesture-based Animations
This feature allows you to create gesture-based animations, such as dragging. The `useDrag` hook from `react-use-gesture` is used in combination with `useSpring` to create a draggable element.
```jsx
import React from 'react';
import { useSpring, animated } from 'react-spring';
import { useDrag } from 'react-use-gesture';
function Draggable() {
const [props, set] = useSpring(() => ({ x: 0, y: 0 }));
const bind = useDrag(({ offset: [x, y] }) => set({ x, y }));
return <animated.div {...bind()} style={{ ...props, width: 100, height: 100, background: 'lightblue' }} />;
}
export default Draggable;
```
Other packages similar to react-spring
framer-motion
Framer Motion is a popular animation library for React that provides a simple API for creating animations and gestures. It is known for its ease of use and powerful features, such as layout animations and shared element transitions. Compared to react-spring, Framer Motion is more focused on providing a high-level API for common animation tasks, while react-spring offers more flexibility and control over the animation physics.
react-transition-group
React Transition Group is a low-level animation library for React that provides more control over the transition states of components. It is often used for simple animations like fading, sliding, and collapsing. Compared to react-spring, React Transition Group is more focused on managing the lifecycle of animations and transitions, while react-spring provides more advanced physics-based animations.
react-move
React Move is an animation library for React that allows you to create complex animations using a declarative syntax. It is designed to work well with data-driven animations and provides a flexible API for creating custom animations. Compared to react-spring, React Move is more focused on data-driven animations and provides a different approach to defining animations using a declarative syntax.
npm install react-spring
Examples: Api demonstration | Native rendering | Single transition | Multiple item transition | Animated Todo MVC | Staggered animation
Why 🤔
React-spring is a wrapper around a cooked down fork of Facebooks animated. It is trying to bridge Chenglou's React-motion and animated, as both have their pros and cons, but definitively could benefit from one another:
React-motion
Animated
So as you see, they're polar opposites and the strengths of one are the weaknesses of another. React-spring inherits React-motions api while you can feed it everything animated can interpolate. It also has support for animateds efficient native rendering.
Default rendering 🏎
Like React-motion by default we'll render the receiving component every frame as it gives you more freedom to animate whatever you like. In many situations this will be ok.
import { Spring } from 'react-spring'
const App = ({ toggle }) => (
<Spring
// Default values, optional ...
from={{ opacity: 0 }}
// Will animate to ...
to={{
// Can be numbers, colors, paths, degrees, percentages, ...
color: toggle ? 'red' : '#00ff00',
start: toggle ? '#abc' : 'rgb(10,20,30)',
end: toggle ? 'seagreen' : 'rgba(0,0,0,0.5)',
stop: toggle ? '0%' : '50%',
scale: toggle ? 1 : 2,
rotate: toggle ? '0deg' : '45deg',
path: toggle
? 'M20,380 L380,380 L380,380 L200,20 L20,380 Z'
: 'M20,20 L20,380 L380,380 L380,20 L20,20 Z',
}}>
{({ color, scale, rotate, path, start, stop, end }) => (
<div style={{ background: `linear-gradient(to bottom, ${start} ${stop}, ${end} 100%)` }}>
<svg style={{ transform: `scale(${scale}) rotate(${rotate})` }}>
<g fill={color}>
<path d={path} />
</g>
</svg>
</div>
)}
</Spring>
)
Don't like the way render props wrap your code? You can always move out component definitions, like so:
const Header = ({ text, ...styles }) => <h1 style={styles}>{text}</h1>
const App = () => (
<Spring to={{ color: 'red' }} text="extra props are spread over the child" children={Header}/>
)
Et voilà! Now you render a animated version of the Header
component! It's actually faster as well since the function isn't recreated on every prop-change.
Native rendering 🚀
If you need more performance then pass the native
flag. Now your component will only render once and all updates will be sent straight to the dom without any React reconciliation passes.
Just be aware of the following conditions:
- You can only animate styles and standard props, the values you receive are opaque objects, not regular values
- Receiving elements must be
animated.[elementName]
, for instance div
becomes animated.div
- You can slap animated values right into styles and props,
style.transform
takes an array
import { Spring, animated } from 'react-spring'
const App = ({ toggle }) => (
<Spring
native
from={{ fill: 'black' }}
to={{
fill: toggle ? '#247BA0' : '#70C1B3',
backgroundColor: toggle ? '#B2DBBF' : '#F3FFBD',
rotate: toggle ? '0deg' : '180deg',
scale: toggle ? 0.6 : 1.5,
path: toggle ? TRIANGLE : RECTANGLE,
}}>
{({ fill, backgroundColor, rotate, scale, path }) => (
<animated.div style={{ backgroundColor }}>
<animated.svg style={{ transform: [{ rotate }, { scale }], fill }}>
<g><animated.path d={path} /></g>
</animated.svg>
</animated.div>
)}
</Spring>
)
If you need to interpolate native styles, use template
. For instance, given that you receive the start of a gradient and its end as animatable values you could do it like so:
import { Spring, animated, template } from 'react-spring'
const Content = ({ start, end }) => (
<animated.h1 style={{ background: template`linear-gradient(${start} 0%, ${end} 100%)` }}>
hello
</animated.h1>
)
const App = () => (
<Spring
native
from={{ start: 'black', end: 'black' }}
to={{ start: '#70C1B3', end: 'seagreen' }}
children={Content} />
)
Transitions 🌑🌒🌓🌔🌕
Use SpringTransition
and pass in your keys
. from
denotes base styles, enter
styles are applied when objects appear, leave
styles are applied when objects disappear. Keys and children have to match in their order! You can again use the native
flag for direct dom animation.
import { SpringTransition } from 'react-spring'
class AppContent extends PureComponent {
state = { items: ['item1', 'item2', 'item3'] }
componentDidMount() {
setTimeout(() => this.setState({ items: ['item1', 'item2', 'item3', 'item4'] }), 2000)
setTimeout(() => this.setState({ items: ['item1', 'item3', 'item4'] }), 4000)
}
render() {
return (
<ul>
<SpringTransition
keys={this.state.items}
from={{ opacity: 0, color: 'black', height: 0 }}
enter={{ opacity: 1, color: 'red', height: 18 }}
leave={{ opacity: 0, color: 'blue', height: 0 }}>
{this.state.items.map(item => styles => <li style={styles}>{item}</li>)}
</SpringTransition>
</ul>
)
}
}
You can use this prototype for two-state reveals, in that case simply render a single child that you can switch out for another.
const App = ({ toggle }) => (
<SpringTransition
keys={toggle ? 'ComponentA' : 'ComponentB'}
from={{ opacity: 0 }}
enter={{ opacity: 1 }}
leave={{ opacity: 0 }}>
{toggle ? ComponentA : ComponentB}
</SpringTransition>
)
Trails/Staggered transitions 👣
Create trailing animations by using SpringTrail.
import { SpringTrail } from 'react-spring'
const App = ({ items }) => (
<SpringTrail from={{ opacity: 0 }} to={{ opacity: 1 }} keys={items.map(item => item.key)}>
{items.map(item => styles => (
<div style={styles}>
{item.text}
</div>
))}
</SpringTrail>
)