![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
react-spring
Advanced tools
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.
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;
```
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 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 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
A set of simple, spring-physics based primitives (as in building blocks) that should cover most of your UI related animation needs once plain CSS can't cope any longer. Forget easings, durations, timeouts and so on as you fluidly move data from one state to another. This isn't meant to solve each and every problem but rather to give you tools flexible enough to confidently cast ideas into moving interfaces.
react-spring is a cooked down fork of Christopher Chedeau's animated (which is used in react-native by default). It is trying to bridge it with Cheng Lou's react-motion. Although both are similarily spring-physics based they are still polar opposites.
Declarative | Primitives | Interpolations | Performance | |
---|---|---|---|---|
React-motion | ✅ | ✅ | ❌ | ❌ |
Animated | ❌ | ❌ | ✅ | ✅ |
React-spring | ✅ | ✅ | ✅ | ✅ |
react-spring builds upon animated's foundation, casting its imperative side out, making it leaner and more flexible. It inherits react-motions declarative api and goes to great lengths to simplify it. It has lots of useful primitives, can interpolate mostly everything and last but not least, can animate by committing directly to the dom instead of re-rendering a component frame-by-frame.
For a more detailed explanation read Why React needed yet another animation library.
A Spring
will move data from one state to another. It remembers the current state, value changes are always fluid.
import { Spring } from 'react-spring'
<Spring from={{ opacity: 0 }} to={{ opacity: 1 }}>
{styles => <div style={styles}>i will fade in</div>}
</Spring>
Transition
watches elements as they mount and unmount, it helps you to animate these changes.
import { Transition } from 'react-spring'
<Transition
keys={items.map(item => item.key)}
from={{ opacity: 0, height: 0 }}
enter={{ opacity: 1, height: 20 }}
leave={{ opacity: 0, height: 0 }}>
{items.map(item => styles => <li style={styles}>{item.text}</li>)}
</Transition>
Given a single child instead of a list you can reveal components with it.
import { Transition } from 'react-spring'
<Transition from={{ opacity: 0 }} enter={{ opacity: 1 }} leave={{ opacity: 0 }}>
{toggle ? ComponentA : ComponentB}
</Transition>
Trail
animates the first child of a list of elements, the rest follow the spring of their previous sibling.
import { Trail } from 'react-spring'
<Trail from={{ opacity: 0 }} to={{ opacity: 1 }} keys={items.map(item => item.key)}>
{items.map(item => styles => <div style={styles}>{item.text}</div>)}
</Trail>
Parallax
allows you to declaratively create page/scroll-based animations.
import { Parallax, ParallaxLayer } from 'react-spring'
<Parallax pages={2}>
<ParallaxLayer offset={0} speed={0.2}>
first Page
</ParallaxLayer>
<ParallaxLayer offset={1} speed={0.5}>
second Page
</ParallaxLayer>
</Parallax>
You'll find varying implementations under /dist/addons. For now there's a time-based animation as well common easings, and IOS'es harmonic oscillator spring. All primitives understand the impl
property which you can use to switch implementations.
import { TimingAnimation, Easing } from 'react-spring/dist/addons'
<Spring impl={TimingAnimation} config={{ delay: 200, duration: 1000, easing: Easing.linear }} ...>
Keyframes
orchestrates animations in a script that you provide. Theoretically you can even switch between primitives, for instance going from a Spring, to a Trail, to a Transition. It tries its best to remember the last state so that animations are additive. Animation can be awaited and return current props. Be warned: the keyframe API is still highly experiemental and can be subject to changes.
import { Keyframes, Spring } from 'react-spring'
<Keyframes script={async next => {
await next(Spring, { from: { opacity: 0 }, to: { opacity: 1 } })
await next(Spring, { to: { opacity: 0 } })
}}>
{styles => <div style={styles}>Hello</div>}
</Keyframes>
The Api is driven by render props (though we do expose imperative Api as well). By principle we offer both render
and children
as well as prop forwardwing (unrecognized props will be spread over the receiving component).
const Header = ({ children, bold, ...styles }) => (
<h1 style={styles}>
{bold ? <b>{children}</b> : children}
</h1>
)
<Spring render={Header} to={{ color: 'fuchsia' }} bold={this.state.bold}>
hello there
</Spring>
You can interpolate almost everything, from numbers, colors (names, rgb, rgba, hsl, hsla), paths (as long as the number of points match, otherwise use custom interpolation), percentages, units, arrays and string patterns:
<Spring to={{
scale: toggle ? 1 : 2,
start: toggle ? '#abc' : 'rgb(10,20,30)',
end: toggle ? 'seagreen' : 'rgba(0,0,0,0.5)',
stop: toggle ? '0%' : '50%',
rotate: toggle ? '0deg' : '45deg',
shadow: toggle ? '0 2px 2px 0px rgba(0, 0, 0, 0.12)' : '0 20px 20px 0px rgba(0, 0, 0, 0.5)',
path: toggle ? 'M20,380 L380,380 L380,380 Z' : 'M20,20 L20,380 L380,380 Z',
vector: toggle ? [1,2,50,100] : [20,30,1,-100],
}}>
![]() | ![]() |
---|---|
Most libs animate by having React recalculate the component-tree on every frame. Here it attempts to animate a component consisting of ~300 sub-components, plowing through the frame budget and causing jank. | React-spring with the native property renders the component only once, from then on the animation will be applied directly to the dom in a requestAnimationFrame-loop, similar to how gsap and d3 do it. |
import { Spring, animated } from 'react-spring'
<Spring native from={{ opacity: 0 }} to={{ opacity: 1 }}>
{styles => <animated.div style={styles}>i will fade in</animated.div>}
</Spring>
More about native rendering and interpolation here.
Click for a combined example repository you can install as well as a collection of code-sandboxes to toy around with online.
If you ever plan to use this library, this should be a must-read. It will go a little deeper into the primitives and how "native" rendering can make a large performance impact (for the better of course).
For annotated prop-types, good for finding out about all the obscure props that i don't want to bore you with (but which might come in handy, you never know).
FAQs
Unknown package
We found that react-spring demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.