I've got something like this:
const [valueA, setValA] = useState(1)
const [valueB, setValB] = useState(1)
const classHandler = (val) => {
if (val<2) {
return 'styles.redButt'
} else if (val===2) {
return 'styles.normalButt'
} else if (val===5) {
return 'styles.greenButt'
} else {
return 'styles.noneButt'
}
}
return (<>
<div className={classHandler(valueA), styles.buttonize}>
FIRST INFO {valueA}
</div>
<div className={classHandler(valueB), styles.buttonize}>
SECOND INFO {valueB}
</div>
</>)
Function doesn't work, but no errors, and second class {styles.buttonize} works just fine! What am I missing?
The comma operator (,) evaluates each of its operands (from left to right) and returns the value of the last operand. In your case classHandler(valueA)
is evaluated but className
will be equal to styles.buttonize (last operand).
If you are using css modules
, this return 'styles.redButt'
, won't work, instead use return styles.redButt
const classHandler = (val) => {
if (val<2) {
return styles.redButt
} else if (val===2) {
return styles.normalButt
} else if (val===5) {
return styles.greenButt
} else {
return styles.noneButt
}
}
<div className={`${classHandler(valueA)} ${styles.buttonize}`}>
FIRST INFO {valueA}
</div>