DEV Community

Cover image for Animations with the Emotion library
Paul Ryan
Paul Ryan

Posted on

Animations with the Emotion library

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

Top comments (7)

Collapse
 
kylefilegriffin profile image
Kyle Griffin • Edited

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

Collapse
 
paulryan7 profile image
Paul Ryan

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

Collapse
 
paulryan7 profile image
Paul Ryan

haha that's fair enough

Collapse
 
vladyn profile image
Vladimir Varbanov

Hi, thanks the useful tutorial. I was wondering how can I achieve animation with transition property and, on user interaction. On Click I want to shrink a div element by adding to it an additional class name to the same element with className. What's happening though is that class is added, but the styles in the styled component, where I state: '&.colapsed' { height: 0 } isn't applied.

Collapse
 
quintisimo profile image
Quintus Cardozo

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

Collapse
 
paulryan7 profile image
Paul Ryan

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>
Collapse
 
quintisimo profile image
Quintus Cardozo

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