Security News
Fluent Assertions Faces Backlash After Abandoning Open Source Licensing
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
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.
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 } from 'react-spring'
<Parallax pages={2}>
<Parallax.Layer offset={0} speed={0.2}>
first Page
</Parallax.Layer>
<Parallax.Layer offset={1} speed={0.5}>
second Page
</Parallax.Layer>
</Parallax>
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>
For a raw documentation of all possible properties look here.
You can interpolate almost everything, from numbers, colors, svg-paths, percentages, arrays to 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',
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],
}}>
A couple of extra props you might be interested in are onRest
, which fires once the animations stops, onFrame
, which fires on every frame and gives you the animation value, reset
, which literally resets the spring so that it goes through from
to to
again, immediate
which can enforce values to spring to their to-values immediately (can be true
for a zero-time spring or an array where you can pass the key-names individually).
Don't like the way render props wrap your code?
const Header = ({ children, bold, ...styles }) => (
<h1 style={styles}>
{bold ? <b>{children}</b> : children}
</h1>
)
<Spring render={Header} to={{ color: 'fuchsia' }} bold>
hello there
</Spring>
Et voilร ! Header
animates on prop changes! Props that Spring
doesn't recognize will be spread over the receiving component, in this example bold
, but it also includes children
if you use render
to refer to the render-child.
By default we'll render the receiving component every frame as it gives you more freedom to animate. In situations where that becomes expensive add the native
flag and animations will now be applied directly to the dom. The flag is available for all primitives (Spring, Transition & Trail, Parallax is native by design).
Just be aware of the following conditions:
animated.[elementName]
, for instance div
becomes animated.div
template
string literal or interpolate
import { Spring, animated, template } from 'react-spring'
<Spring native to={{ path, rotate, scale }}>
{({ rotate, scale, path }) => (
<animated.svg style={{ transform: template`rotate(${rotate}) scale(${scale})` }}>
<g><animated.path d={path} /></g>
</animated.svg>
)}
</Spring>
You have several interpolation options, not just template
. interpolate
can be called on the value itself or as a stand-alone function which can read multiple values. It accepts either a function which receives the animation value(/s), or a range.
import { Spring, animated, interpolate } from 'react-spring'
<animated.svg
style={{
transform: interpolate([x, y], (x, y) => `translate(${x}px, ${y}px)`),
color: time.interpolate({ inputRange: [0, 1], outputRange: ['red', 'rgba(1, 50, 210, 0.5)'] })
}}>
<g><animated.path d={time.interpolate(customSvgInterpolator)} /></g>
</animated.svg>
Animates children as they mount and unmount. 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! The keys are the same that you would provide in any other looping situation.
import { Transition } from 'react-spring'
<ul>
<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>
</ul>
You can use this prototype for two-state reveals, simply render a single child that you can switch out for another. You don't have to pass keys for this one.
<Transition from={{ opacity: 0 }} enter={{ opacity: 1 }} leave={{ opacity: 0 }}>
{toggle ? ComponentA : ComponentB}
</Transition>
For more complex animations you can return per-object styles individually. Let Transition know the actual data by passing it raw to items
, either pass your keys like always or give it an accessor. And for more control, there's update
which fires for nodes that are neither entering nor leaving.
<Transition
items={items}
keys={item => item.key}
from={item => ({ opacity: 0 })}
enter={item => ({ opacity: 1 })}
update={item => ({ opacity: 0.5 })}
leave={item => ({ opacity: 0 })}>
{items.map(item => styles => <li style={styles}>{item.text}</li>)}
</Transition>
Trail
animates the first child of the list you pass, the others will follow in a trailing motion. The api is similar to Transition
though it will assume your list is fixed.
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
creates a scroll container. Throw in any amount of layers and it will take care of moving them in accordance to their offsets and speeds.
Parallax.pages
determines the total space of the inner content where each page takes 100% of the visible container. Layer.offset
determines where the layer will be at when scrolled to (0=start, 1=1st page, ...). Layer.speed
shifts the layer in accordance to its offset, values can be positive or negative.
import { Parallax } from 'react-spring'
<Parallax pages={3} scrolling={false} horizontal ref={ref => this.parallax = ref}>
<Parallax.Layer offset={0} speed={0.5}>
<span onClick={() => this.parallax.scrollTo(1)}>
Layers can contain anything
</span>
</Parallax.Layer>
</Parallax>
FAQs
Unknown package
The npm package react-spring receives a total of 595,121 weekly downloads. As such, react-spring popularity was classified as popular.
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
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.