How to pass props to keyframes in styled-component with react?

this example for animation for the progress bar for using typescript

    export const animatedProgress = (y:number) => keyframes`
0%{
      width: 0%;
    }
    25%{
        width:  ${y >= 25 ? 25 : y}%;
    }
    50%{
      width:  ${y >= 50 ? 50 : y}%;
    }
    75%{
      width:  ${y >= 75 ? 75 : y}%;
    }
    100%{
      width:  ${y >= 100 ? 100 : y}%;
    }

`;

export const ProgressAnimated = styled("div")<progressAnimated>`

animation : ${props => animatedProgress(props.value)} 3s linear;
`;

You can make moveVertically a function. Please consider code below:

const moveVertically = (y) => keyframes`
    0% {
        transform : translateY(0px) 
    }
    100% {
        transform : translateY(${y}px)
    }
`;

const BallAnimation = styled.g`
    animation : ${props => moveVertically(props.y)} ${props => props.time}s linear
`;

Here you have y in props of BallAnimation. So you can extract it and pass it to moveVertically function which accepts y value as a parameter.


How about making moveVertically a function that returns the keyframes styled component?

That way, you can pass in the prop you want:

const moveVertically = (y) =>
  keyframes`
    0% {
      transform: translateY(0px);
    }
    100% {
      transform: translateY(${y}px);
    }
  `

const BallAnimation = styled.g`
  animation: ${props => moveVertically(props.y)} ${props => props.time}s linear;
`