Search code examples
javascriptreactjsstyled-components

What is the difference between 'styled.div' and 'keyframes' for styled components?


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?


Solution

  • 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.