DEV Community

Ellen Styrélius
Ellen Styrélius

Posted on


styled-components keyframes animations - a very short guide

To create a @keyframes animation and use it with styled-components the first thing you need to do is to import the keyframes helper.

import styled, { keyframes } from 'styled-components';
Enter fullscreen mode Exit fullscreen mode

Just as the div, or any other “element” property that exists on the styled object imported from styled-components, keyframes is a function that you use as a tag for your template literal style declarations.

And just as with the divs and the buttons the result from the tag function is assigned to a variable. This variable is then used to reference the animation in your styled components (and since your keyframes animation is not a React component the variable should be named in camelCase and not PascalCase).

const rotate = keyframes`
  to {
    transform: rotate(360deg);

const InfiniteRotate = styled.div`
  animation: ${rotate} 4s linear infinite;

function Spinner() {
  return <InfiniteRotate>🥴</InfiniteRotate>
Enter fullscreen mode Exit fullscreen mode

It’s not really more complicated than that! And this syntax allows you to export the animation and use it in several places in your app with different durations, iteration counts etc.

P.S. Might be worth noting that keyframes can NOT be used with react-native, but there is a library for that called Animated.

Top comments (0)

One Million Strong

We are an active and inclusive community of over one million registered creators, developers, and tech enthusiasts. Join us.