Animate Styled Components in React

Sara Vieira
InstructorSara Vieira

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

We will be using the keyframes function from styled-components to animate the position and rotation of an h1.

Like styling using the global variable, we set the keyframes keyword to a variable and inside of the backticks, we set what we want our element to do. Then in a custom element, we set animation to our custom keyframes variable.

Sara Vieira: [0:01] Let's import keyframes from styled-components. We can import it like this and now to use it, to create animations with styled-components we say const and then move. That's the name of it, because I'm just going to move it.

[0:12] I'm going to say keyframes, open up the back ticks and then write an animation like I would in normal CSS. I can say from, and I'm going to say transform, and I'll say translateX. It starts at zero like this. I'm just going to copy this since it's easier than writing it, and I'm very lazy. I'm going to say two, and I'm going to say 100 percent, so that it goes from one side to the other.

[0:41] How do we use this? Obviously, it's not animating. I come here and I say animation, and the main difference is that you can't just type move, you have to interpolate it like so, so ${move}, then the duration, two seconds, the transitioning, so ease. Then I'm just going to say infinite because I wanted to run forever. If I do this, you can see that now we have this animation. You can also add a rotate, for example, so rotate. I'm going to start it at zero and say rotate. I'm going to start it at 45, and I have to put deg.

[1:15] Now it does this, which is terrible, but it is an animation. This is how you can animate the styled-components.