import {Motion, spring} from 'react-motion';
// In your render...
<Motion defaultStyle={{x: 0}} style={{x: spring(10)}}>
{value => <div>{value.x}</div>}
</Motion>
Animate a counter from 0
to 10
. For more advanced usage, see below.
-
Npm:
npm install --save react-motion
-
Bower: do not install with
bower install react-motion
, it won't work. Usebower install --save https://npmcdn.com/react-motion/bower.zip
. Or inbower.json
:
{
"dependencies": {
"react-motion": "https://npmcdn.com/react-motion/bower.zip"
}
}
then include as
<script src="bower_components/react-motion/build/react-motion.js"></script>
- 1998 Script Tag:
<script src="https://npmcdn.com/react-motion/build/react-motion.js"></script>
(Module exposed as `ReactMotion`)
- Build it yourself from the repo:
git clone https://github.com/chenglou/react-motion.git
cd react-motion
npm install
npm run prerelease
To try the demos locally with hot reloading, run npm start
. Don't forget to compile for production when you test your animation's performance!
For React-native: previous react-motion v0.3.* supported a dedicated build for RN, which has now been made obsolete since RN v0.18. This library should Just Work under the new React-Native 0.18+.
- Simple Transition
- Chat Heads
- Draggable Balls
- TodoMVC List Transition
- Photo Gallery
- Spring Parameters Chooser
- Water Ripples
- Draggable List
For 95% of use-cases of animating components, we don't have to resort to using hard-coded easing curves and duration. Set up a stiffness and damping for your UI element, and let the magic of physics take care of the rest. This way, you don't have to worry about petty situations such as interrupted animation behavior. It also greatly simplifies the API.
This library also provides an alternative, more powerful API for React's TransitionGroup
.
Coming from 0.3. to 0.4.0? Here's the upgrade guide.*
Exports:
spring
.Motion
StaggeredMotion
TransitionMotion
presets
Here's the well-annotated public Flow type definition file (you don't have to use Flow with React-motion, but the types help document the API below).
Used in conjunction with the components below. Specifies the how to animate to the destination value, e.g. spring(10, {stiffness: 120, damping: 17})
means "animate to value 10, with a spring of stiffness 120 and damping 17".
-
val
: the value. -
config
: optional, for further adjustments. Possible fields:stiffness
: optional, defaults to170
.damping
: optional, defaults to26
.precision
: optional, defaults to0.01
. Specifies both the rounding of the interpolated value and the speed (internal).
It's normal not to feel how stiffness and damping affect your spring; use Spring Parameters Chooser to get a feeling. Usually, you'd just use the list of tasteful stiffness/damping presets below.
Commonly used spring configurations used like so: spring(10, presets.wobbly)
or spring(20, {...presets.gentle, precision: 0.1})
. See here.
<Motion defaultStyle={{x: 0}} style={{x: spring(10)}}>
{interpolatingStyle => <div style={interpolatingStyle} />}
</Motion>
Required. 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 component's existence. The meaning of the values:
- an
OpaqueConfig
returned fromspring(x)
: interpolate tox
. - a
number
x
: jump tox
, do not interpolate.
Optional. The PlainStyle
type maps to number
s. Defaults to an object with the same keys as 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
).
Required function.
-
interpolatedStyle
: the interpolated style object passed back to you. E.g. if you gavestyle={{x: spring(10), y: spring(20)}}
, you'll receive asinterpolatedStyle
, at a certain time,{x: 5.2, y: 12.1}
, which you can then apply on yourdiv
or something else. -
Return: must return one React element to render.
Animates a collection of items whose values depend on each other, creating a natural, springy, "staggering" effect like so. This is preferred over hard-coding a delay for an array of Motions
to achieve a similar (but less natural-looking) effect.
<StaggeredMotion
defaultStyles={[{h: 0}, {h: 0}, {h: 0}]}
styles={prevInterpolatedStyles => prevInterpolatedStyles.map((_, i) => {
return i === 0
? {h: spring(100)}
: {h: spring(prevInterpolatedStyles[i - 1].h)}
})}>
{interpolatingStyles =>
<div>
{interpolatingStyles.map((style, i) =>
<div key={i} style={{border: '1px solid', height: style.h}} />)
}
</div>
}
</StaggeredMotion>
Aka "the current spring's destination value is the interpolating value of the previous spring". Imagine a spring dragging another. Physics, it works!
Required function. Don't forget the "s"!
-
previousInterpolatedStyles
: the previously interpolating (array of) styles (undefined
at first render, unlessdefaultStyles
is provided). -
Return: must return an array of
Style
s containing the destination values, e.g.[{x: spring(10)}, {x: spring(20)}]
.
Optional. Similar to Motion
's defaultStyle
, but an array of them.
Required function. Similar to Motion
's children
, but accepts the array of interpolated styles instead, e.g. [{x: 5}, {x: 6.4}, {x: 8.1}]
Helps you to do mounting and unmounting animation.
You have items a
, b
, c
, with their respective style configuration, given to TransitionMotion
's styles
. In its children
function, you're passed the three interpolated styles as params; you map over them and produce three components. All is good.
During next render, you give only a
and b
, indicating that you want c
gone, but that you'd like to animate it reaching value 0
, before killing it for good.
Fortunately, TransitionMotion
has kept c
around and still passes it into the children
function param. So when you're mapping over these three interpolated styles, you're still producing three components. It'll keep interpolating, while checking c
's current value at every frame. Once c
reaches the specified 0
, TransitionMotion
will remove it for good (from the interpolated styles passed to your children
function).
This time, when mapping through the two remaining interpolated styles, you'll produce only two components. c
is gone for real.
const Demo = React.createClass({
getInitialState() {
return {
items: [{key: 'a', size: 10}, {key: 'b', size: 20}, {key: 'c', size: 30}],
};
},
componentDidMount() {
this.setState({
items: [{key: 'a', size: 10}, {key: 'b', size: 20}], // remove c.
});
},
willLeave() {
// triggered when c's gone. Keeping c until its width/height reach 0.
return {width: spring(0), height: spring(0)};
},
render() {
return (
<TransitionMotion
willLeave={this.willLeave}
styles={this.state.items.map(item => ({
key: item.key,
style: {width: item.size, height: item.size},
}))}>
{interpolatedStyles =>
// first render: a, b, c. Second: still a, b, c! Only last one's a, b.
<div>
{interpolatedStyles.map(config => {
return <div key={config.key} style={{...config.style, border: '1px solid'}} />
})}
</div>
}
</TransitionMotion>
);
},
});
First, two type definitions to ease the comprehension.
-
TransitionStyle
: an object of the format{key: any, data?: any, style: Style}
.-
key
: required. The ID thatTransitionMotion
uses to track which configuration is which across renders, even when things are reordered. Typically reused as the componentkey
when you map over the interpolated styles. -
data
: optional. Anything you'd like to carry along. This is so that when the previous section example'sc
disappears, you still get to accessc
's related data, such as the text to display along with it. -
style
: required. The actual starting style configuration, similar to what you provide forMotion
'sstyle
. Maps keys to either a number or anOpaqueConfig
returned byspring()
.
-
-
TransitionPlainStyle
: similar to above, except thestyle
field's value is of typePlainStyle
, aka an object that maps to numbers.
- styles: Array<TransitionStyle> | (previousInterpolatedStyles: ?Array<TransitionPlainStyle>) => Array<TransitionStyle>
Required. Accepts either:
-
an array of
TransitionStyle
configs, e.g.[{key: 1, style: {x: spring(0)}}, {key: 2, style: {x: spring(10)}}]
. -
a function similar to
StaggeredMotion
, taking the previously interpolating styles (undefined
at first call, unlessdefaultStyles
is provided), and returning the previously mentioned array of configs. You can do staggered mounting animation with this.
Optional. Similar to the other components' defaultStyle
/defaultStyles
.
Required function. Similar to other two components' children
. Receive back an array similar to what you provided for defaultStyles
, only that each style
object's number value represent the currently interpolating value.
Optional. Defaults to () => null
. The magic sauce property.
-
styleThatLeft
: the e.g.{key: ..., data: ..., value: ...}
object from thestyles
array, identified bykey
, that was present during a previous render, and that is now absent, thus triggering the call towillLeave
. -
Return:
null
to indicate you want theTransitionStyle
gone immediately. AStyle
object to indicate you want to reach transition to the specified value(s) before killing theTransitionStyle
.
Optional. Defaults to styleThatEntered => stripStyle(styleThatEntered.style)
. Where stripStyle
turns {a: spring(10), b: spring(20)}
into {a: 10, b: 20}
.
-
styleThatEntered
: similar towillLeave
's, except theTransitionStyle
represents the object whosekey
value was absent during the lastrender
, and that is now present. -
Return: a
defaultStyle
-likePlainStyle
configuration, e.g.{a: 0, b: 0}
, that serves as the starting values of the animation. Under this light, the default provided means "a style config that has the same starting values as the destination values".
Note that willEnter
and defaultStyles
serve different purposes. willEnter
only triggers when a previously inexistent TransitionStyle
inside styles
comes into the new render.
- How do I set the duration of my animation?
Hard-coded duration goes against fluid interfaces. If your animation is interrupted mid-way, you'd get a weird completion animation if you hard-coded the time. That being said, in the demo section there's a great Spring Parameters Chooser for you to have a feel of what spring is appropriate, rather than guessing a duration in the dark.
- How do I unmount the
TransitionMotion
container itself?
You don't. Unless you put it in another TransitionMotion
...
- How do I do staggering/chained animation where items animate in one after another?
See StaggeredMotion
- My
ref
doesn't work in the children function.
React string refs won't work:
<Motion style={...}>{currentValue => <div ref="stuff" />}</Motion>
This is how React works. Here's the callback ref solution.