DEV Community

Ellen Styrélius
Ellen Styrélius

Posted on

8 2

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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more