React motion

As soon as the complexity of the animations grows, or when we need animations that depend on other animations, or, which is more advanced, when we need to apply some physics-based behavior to our components, we realize that the transition group is not helping us enough, so we may consider using a third-party library.

The most popular library to create animations in React is react-motion, which is maintained by Cheng Lou. It provides a very clean and easy API that gives us a very powerful tool to create any animations.

To use it, we first have to install it:

  npm install --save react-motion

Once the installation is successfully completed, we need to import the motion component and the spring function. Motion is the component we will use to wrap the elements we want to animate, while the function is a utility that can interpolate a value from its initial state to the final one:

  import { Motion, spring } from 'react-motion';

Let's look at the code:

  const Transition = () => ( 
<Motion
defaultStyle={{ opacity: 0.01 }}
style={{ opacity: spring(1) }}
>
{interpolatingStyle => (
<h1 style={interpolatingStyle}>Hello React</h1>
)}
</Motion>
);

There are a lot of interesting things here.

First, you may have noticed that this component uses the function as a child pattern (see Chapter 4, Compose All the Things ), which is a pretty powerful technique to define children that receive values at runtime.

Then, we can see that the Motion component has two attributes: the first one is defaultStyle, which represents the initial style.

Again, we set the opacity to 0.0.1 to hide the element and start the fade.

The style attribute represents the final style instead, but we do not set the value directly; instead we use the spring function so that the value is interpolated from the initial state to the final one.

On each iteration of the spring function, the child function receives the interpolated style for the given point in time and, just by applying the received object to the style attribute of the component, we can see the transition of the opacity.

This library can do some more cool stuff, but the first things to learn about are the basic concepts, and this example should clarify them.

It is also interesting to compare the two different approaches of the transition group and react-motion to be able to choose the right one for the project you are working on.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset