Animations with the Emotion library

Paul Ryan - Apr 28 '19 - - Dev Community

Hey guys, this is a very short article just to show you how you can add animations if you are styling your components with emotion.

The final result is here (this is the sandbox I used when creating my first emotion tutorial):

The first thing you need to do is import keyframes:

import { keyframes } from "@emotion/core";

The next thing we want to do is to create our animation, let's create a bounce effect:

const Hop = keyframes`
 from, 20%, 53%, 80%, to {
    transform: translate3d(0,0,0);
  }

  40%, 43% {
    transform: translate3d(0, -30px, 0);
  }

  70% {
    transform: translate3d(0, -15px, 0);
  }

  90% {
    transform: translate3d(0,-4px,0);
  }
`;

This is similar to how you style components with emotion but instead of using styled, we use keyframes.

We now need to create a styled component that will use this animation, let's wrap this animation around some text so we name as follows:

const Text = styled("text")`
  animation: ${Hop} 1s linear infinite;
`;

God, I love template literals!

Only one more step, and that is to swap in our Text constant, which basically means replacing the div around the text with Text like so:

<Text className="country">
  <span>Iceland</span>
</Text>

And magically our text is now bouncing, how simple was that? Now go ahead and animate some shiz :D

. . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player