adding two classes (active class) using styled-components

peter flanagan picture peter flanagan · Feb 7, 2018 · Viewed 15.5k times · Source

I am migrating from css to styled-components.

My react component looks like the following:

class Example extends React.Component {

  ........code here

  render() {
    return (
      <div 
        className={ this.state.active ? "button active" : "button" }
        onClick={ this.pressNumber }
       >
          <Number>{ this.props.number }</Number>
      </div>
    )
  }
}

const Number = styled.div`
  color: #fff;
  font-size: 26px;
  font-weight: 300;
`;

and my css looks like this:

.button {
  height: 60px;
  width: 60px;
}

.active {
  animation-duration: 0.5s;
  animation-name: highlightButton;
}


@keyframes highlightButton {
  0%   {
    background-color: transparent;
  }
  50%  {
    background-color: #fff;
  }
  100%  {
    background-color: transparent;
  }
}

Does anyone know how I can add the active class/add two classes to an element using styled-components? Nothing is jumping out at me from the docs.

If anything is unclear or further information is required please let me know.

Answer

treyhakanson picture treyhakanson · Feb 8, 2018

The template literals in styled components can access props:

const Button = styled.button`
  height: 60px;
  width: 60px;
  animation: ${
      props => props.active ?
          `${activeAnim} 0.5s linear` :
          "none"
  };
`;

 ...
 <Button active={this.state.active} />
 ...

Reference here

And to add the keyframes animation, you'll need to use the keyframes import:

import { keyframes } from "styled-components";

const activeAnim = keyframes`
    0%   {
        background-color: transparent;
    }
    50%  {
        background-color: #fff;
    }
    100%  {
        background-color: transparent;
    }
`;

Reference here