Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styled-Components - Pass Props / Theme to keyframes?

Trying some stuff with styled-components & keyframes. It's about animating text color. It does work when using hex codes or css color names. However, I'd like to use the colors I've got defined in my theme. It doesn't seem to work though? How can I use props here?

const changeColor = keyframes`
    0% {
    color: ${props => props.theme.color.somecolor};
    }
    100% {
      color: ${props => props.theme.color.somecolor};
    }
`;

const ColorChange = css`
  -webkit-animation: ${changeColor} 3s infinite;
  -moz-animation: ${changeColor} 3s infinite;
  -o-animation: ${changeColor} 3s infinite;
  -ms-animation: ${changeColor} 3s infinite;
  animation: ${changeColor} 3s infinite;
`;

const ColorChangeComponent = styled.span`
  ${ColorChange}
`;
like image 564
R. Kohlisch Avatar asked Aug 06 '26 07:08

R. Kohlisch


1 Answers

I suppose you could return your keyframes from a function that accepts the props as an argument:

const getChangeColor = (props) => keyframes`
  0% {
    color: ${props.theme.color.somecolor};
  }
  100% {
    color: ${props.theme.color.somecolor};
  }
`;

...and then pass the props in to the function when you call it:

const ColorChange = css`
  -webkit-animation: ${props => getChangeColor(props)} 3s infinite;
  -moz-animation: ${props => getChangeColor(props)} 3s infinite;
  -o-animation: ${props => getChangeColor(props)} 3s infinite;
  -ms-animation: ${props => getChangeColor(props)} 3s infinite;
  animation: ${props => getChangeColor(props)} 3s infinite;
`;

...or to simplify:

const ColorChange = css`
  -webkit-animation: ${getChangeColor} 3s infinite;
  -moz-animation: ${getChangeColor} 3s infinite;
  -o-animation: ${getChangeColor} 3s infinite;
  -ms-animation: ${getChangeColor} 3s infinite;
  animation: ${getChangeColor} 3s infinite;
`;

...or maybe even cut down on the number of function calls:

const ColorChange = css`
  ${props => {
    const changeColor = getChangeColor(props);
    return `
      -webkit-animation: ${changeColor} 3s infinite;
      -moz-animation: ${changeColor} 3s infinite;
      -o-animation: ${changeColor} 3s infinite;
      -ms-animation: ${changeColor} 3s infinite;
      animation: ${changeColor} 3s infinite;
    `;
  }}
`;

Hope this helps.

like image 75
Steve Holgado Avatar answered Aug 08 '26 21:08

Steve Holgado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!