React Motion is a popular library for animations in React. It makes use of physics to create animations that feel natural. All we have to do to create realistic animations is provide values for stiffness and damping and React Motion takes care of the rest.
In this post we’ll go over the basics of using the library to animate the scaling of a simple Card component. We’ll make use of styled-components for our Card’s styling. We’ll then go over a simple example of animating components as a function of state.
Just add the react-motion package to your project using npm or Yarn. Here we’ll also make use of styled-component, so we’ll add that too:
To create a simple demo, our App component will just render two Card components:
Notice how we can use style-component’s injectGlobal to inject some global styles.
And here’s all the components that make up our Card component:
Now, say we can to animate the cards in when they first mount. Let’s use React Motion’s Motion component to accomplish this:
As you can see, the Motion component makes use of the render prop pattern. It expects a function as its children prop and the function receives the interpolatedStyle
that contains the current interpolated values. Here we pass the interpolated scale value to a scale prop.
We can make use of this scale prop in our style-component like this:
The Motion component takes an optional defaultStyle prop and a required style prop. The style prop is derived using the spring helper function. Spring takes a value to spring to, and an optional config object with values for stiffness, damping and precision. When no config object is passed to spring, the stiffness defaults to 170 and the damping defaults to 26.
In the previous example we pass a scale prop that then gets used by a styled-component, but we could just as well animate inline styles. Here for example we render a h1 element that springs into view:
Using React Motion makes it just as easy to define animations that are a function of the state.
In the following example, we first animate our h1 element into view when the App component mounts, and then provide buttons that call methods to change the state, which controls the animation on the element:
💃 Now go ahead and make things move! In a future post we’ll explore the rest of the API made available with React Motion (StaggeredMotion, TransitionMotion and presets).
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!