loading...
Cover image for Animations with the Emotion library

Animations with the Emotion library

paulryan7 profile image Paul Ryan ・1 min read

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

Posted on by:

paulryan7 profile

Paul Ryan

@paulryan7

Developer hailing from Ireland, love all things JS and starting to fall in love with SVGs!

Discussion

markdown guide
 

Might be worth renaming the article. I was looking for more of a UX/intuition approach to animation. Didn't expect a JS import called 'emotion' xD

 

Renamed, I ask the guys in work and they thought the same as you XD

 
 

Is there an advantage of using the keyframes export in emotion over just defining the @keyframes in line with the css?

 

If you were to define it in the CSS it wouldn't be reusable so any place you need to use the animation you would need to duplicate the code. You could then pop it in easily like this:

<div
    css={css`
      animation: ${hop} 1s ease infinite;
    `}
  >
    some bouncing text!
  </div>
 

Ahh I see. I'm just getting into emotion and this post was quiet helpful