0
votes

I am currently having an issue with 'keyframes' for styled components. I have come to understand how to use props in a 'styled.div', but I have not been able to use props in a 'keyframes' component.

I know the following example is a bit basic, but it gets the point across that I'm trying to make. What is wrong with the 'keyframes' version here:

const HomePageDiv = styled.div`
    background: ${(props) => `red`};
`;

const backgroundChange = keyframes`
    0%{
        background: ${(props) => `blue`};
    }
`;

Here the 'styled.div' component will render a red background, but if I include the keyframes animation, it is completely ignored. On the other hand, if I were to include the following keyframes animation:

const backgroundChange = keyframes`
    0%{
        background: blue;
    }
`;

I would have a perfect fade from blue to red. This has led me to believe that the 'keyframes' and 'styled.div' components have different syntax for props usage. Could someone help me understand the difference?

2

2 Answers

0
votes

To access props in keyframes you need to pass keyframe prop to your component.

Working example:

const rotate = keyframes`
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(${props => props.rotation || '360deg'});
  }
`

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

// Usage:

<RotatingBox rotation="180deg" />

This "issue" was highlighted in ticket 397

0
votes

I have finally found a solution to my question. Matthew Barbara's solution didn't work for me, I'm not sure why, but I did find the solution in ticket 397.

This is how I applied the solution to my own code:

import styled, {keyframes} from 'styled-components';

const backgroundChange = (props) => keyframes`
    0%{
        background: ${props.color1};
    }
`;

const HomePageDiv = styled.div`
    height: 100vh;
    width: 100vw;
    display: flex;
    flex-direction: column;
    position: absolute;
    overflow: hidden;
    animation: ${backgroundChange} 2s linear forwards 1;
`;

export default HomePageDiv;

This will properly pass the props into keyframes, the standard notation of ${} will be needed to use these props. These props must be passed through your component, and of course the keyframes variable name must be passed into your animation.