Home > database >  multiple conditions for styling with Css modules
multiple conditions for styling with Css modules

Time:01-08

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>

CodePudding user response:

<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

CodePudding user response:

I would probably create a variable called classes and set its value and logic above your JSX return statement. Then you could simply set classname={classes} in your boxes.

let classes = 'small'; 

if(hover) {
    classes = 'big'
} else if (anyCardHovered) {
    classes = 'medium'
} else {
    classes = 'small'
}
  • Related