Search code examples
cssreactjsnext.jsjsxcss-modules

multiple conditions for styling with Css modules


I am trying to set multiple conditions with ternary operator to style an element using Css modules. I can't find the exact syntax. is it even possible? there are some boxes that have 3 sizes , their default small size, the big size for the one that's hovered, and the medium size when at least one of them is hovered.

import style from './styles.module.sass'
const Slider =()=>{
const [hover,isHovered]=useState(false);
const [anyCardHovered,setAnyCardHovered]=useState(false)
return 

<div className={`{ hover? ${style.hoveredBox}: anyCardHovered? ${style.smallBox}: style.box}`>
  
</div>

Solution

  • <div className={hover 
      ? style.hoveredBox
      : anyCardHovered
         ? style.smallBox
         : style.box
    }></div>
    

    Another way:

    /* Bits: hover, anyCardHovered */
    const classNames = [
      style.box,        // 00
      style.smallBox,   // 01
      style.hoveredBox, // 10
      style.hoveredBox  // 11
    ];
    
    <div className={classNames[hover << 1 | anyCardHovered]}>
    </div>
    

    More details in: https://blog.uidrafter.com/bitwise-table-lookup