Perplexityy
Perplexityy

Reputation: 569

Trigger animation on props with styled components

I am trying to run an animation on one of my components when one of the props is equal to true. However, I am getting an error that 'flash is not a function'.

https://codesandbox.io/s/wizardly-moser-tet99?file=/src/App.js:0-606

import React, { useState } from "react";
import styled, {keyframes} from "styled-components";

const flash = keyframes`
  from {
      opacity: 0;
      }

      to {
      opacity: 1;
      }
`;

const StyledTile = styled.div`
    width: 100px;
    height: 100px;
    background-color: pink;
    animation: ${props => props.animate ? flash `0.3s linear 3` : `null`};
`

export default function App() {

  const [doAnimate, setDoAnimate] = useState(false);
  return (
    <div className="App">
      <StyledTile animate = {doAnimate}/>
      <button onClick = {() => setDoAnimate(true)}/>
    </div>
  );
}

Upvotes: 5

Views: 4528

Answers (2)

Rokata
Rokata

Reputation: 1229

Seems like the syntax you're using is not supported by styled-components, check this link out:

Keyframes are lazily injected when they're used, which is how they can be code-splitted, so you have to use the css helper for shared style fragments

Here's a working example. So I had to wrap the animation in that css helper.

Upvotes: 1

Mohamed Wagih
Mohamed Wagih

Reputation: 1456

I used the css helper as the docs states here.

const StyledTile = styled.div`
  width: 100px;
  height: 100px;
  background-color: pink;
  animation: ${props =>
    props.animate &&
    css`
      ${flash} 0.3s linear 3
    `};
`;

And here's the sandbox

Upvotes: 9

Related Questions