Christian Nwamba: Start with importing useSpring from the react-spring library. Next, create an animation by calling this useSpring function. This function takes in a callback function. This callback function returns an object or a list of CSS properties that you would like to animate.
For example, if you want to animate the width property from 0to 100, you specify where you want this property to be animated. You can also specify a from object, which tells react-spring where this animation to start from. For the width of this element we want it to start from 0What useSpring returns are the animated properties, which you can then apply to an element. The object returned from the useSpring function also can be used to specify the animation configuration. For instance, if I want this animation to last for three seconds, can add a config object. Inside this object, I would specify the duration property, which I would set to 3,000 milliseconds.
To use the animated values that are returned from useSpring, we have to import the animated object from react-spring. This is because we cannot use animations directly on normal HTML elements or normal JSX elements. Instead, useSpring comes bonded with its own element, which understands the values that are returned from useSpring.
Now we can take the props that was returned from useSpring and set the style prop of our element to this props. To be specific, we want to set the width to props.width. We can't just set the value 0to 100 to width because we need to specify whether that's in pixels or in percentage.
To do that, we can use the interpolate method and set the value that interpolate receives to the value of the width. In this case, we want to set it to from 0to 100 percent. If we reload the browser, we should see that the animation goes from A all the way to B at the rate of three seconds.
As a recap, what we did was to import react-spring libraries, specifically useSpring, animated. Then we create an animation using the useSpring method.
This animation takes in the two properties which is where do we want to animate to. It takes the from property, where do you want to start animation from. Then some configuration if we need to change the default area of the useSpring.
The useSpring properties, which are basically the animated values. You can set these animated values using the animated element that you get from react-spring as a whole. Remember to interpolate the values if you need the contact net pixels or percentage of these values.