1

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?

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Yesss! Thank You! I know I was close.... but without your help... ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.