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)
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
haha that's fair enough
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.
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:
Ahh I see. I'm just getting into emotion and this post was quiet helpful