Search code examples
reactjsstyled-components

styled-components toggle classes


this.state.checkBool is true / false

The HTML structure like this, toggle class1 and class2

<div class='common class1'>
<div class='common class2'>

css looks like

common {
  display: block;
  background: grey;
}

.class1 {
  position: absolute;
  left: 1px;
  right: auto;
  top: 2px;
  background: blue;
}


.class2 {
  position: absolute;
  left: auto;
  top: 2px;
  right: 30px;
  background: yellow;
}

The styled component

const Wrapper = styled.div`
  display: block;
  background: grey;

  // Should this part use props to check true or false?

  ${prosp => } 
`

I am stuck on how to toggle classes

<Wrapper toggle={this.state.checkBool ? class1 :class2 }/>

Solution

  • You want to keep all the CSS in the styled.div and use the toggle prop to decide which CSS you should use for the component depending on its value.

    Example

    const Wrapper = styled.div`
      display: block;
      background: grey;
      ${props => {
        if (props.toggle) {
          return `
            position: absolute;
            left: 1px;
            right: auto;
            top: 2px;
            background: blue;
          `;
        } else {
          return `
            position: absolute;
            left: auto;
            top: 2px;
            right: 30px;
            background: yellow;
          `;
        }
      }}
    `;
    
    class App extends React.Component {
      state = { checkBool: false };
    
      componentDidMount() {
        setTimeout(() => {
          this.setState({ checkBool: true });
        }, 1000);
      }
    
      render() {
        return <Wrapper toggle={this.state.checkBool}> Foo </Wrapper>;
      }
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
    
    <div id="root"></div>