Search code examples
cssstyled-components

How can I use animation in styled-components css``?


I read documents, and I used keyframes`` for declare css animation. But I got error message like this:

Please wrap your string in the css`` helper which ensures the styles are injected correctly.

So, I wrapped animation with css`` instead keyframes``, but animation didn't work.

const rippleAnimation = css`
  0% {
    transform: translate(-50%, -50%) scale(1);
  }

  100% {
      transform: translate(-50%, -50%) scale(var(--material-scale));
      opacity: 0;
  }
`;

This didn't work well.

I don't know I wrote perfectly...

ordinary code(error about keyframes) :

const rippleAnimation = keyframes`
  0% {
    transform: translate(-50%, -50%) scale(1);
  }

  100% {
      transform: translate(-50%, -50%) scale(var(--material-scale));
      opacity: 0;
  }
`;

Solution

  • You can do it like this. Create keyframes in CSS. And add the keyframes with js. You can also add this keyframe after clicking in js.

    const hello = document.querySelector(".hello")
    hello.style.animation = "5s colorChange linear infinite"
    .hello {
      color: #000000;
    }
    
    @keyframes colorChange {
      0% {
        color: black;
      }
      50% {
        color: red;
      }
      100% {
        color: black;
      }
    }
    <h1 class="hello">Hello World</h1>