2

I have a React application and want to change a CSS class when one condition is met or another. How do I do this?

So, if validation or validationNoExist is false then the CSS class should be input-form-validation-wrong, if both are correct then the first class is selected.

Here is my code:

<input type="email"  className={validation || validationNoExist ? 'input-form' : 'input-form-validation-wrong'} placeholder="E-Mail" />

2 Answers 2

2

This may just be an issue of grouping the logical operator so they are evaluated as a unit for the condition test for the ternary. They both need to be true for the ternary to return "input-form".

<input
  type="email"
  className={(validation && validationNoExist) ? 'input-form' : 'input-form-validation-wrong'}
  placeholder="E-Mail"
/>

console.log((false && false) ? 'input-form' : 'input-form-validation-wrong');
console.log((true && false) ? 'input-form' : 'input-form-validation-wrong');
console.log((false && true) ? 'input-form' : 'input-form-validation-wrong');
console.log((true && true) ? 'input-form' : 'input-form-validation-wrong');

2

<input type="email"  className={(validation || validationNoExist) ? 'input-form' : 'input-form-validation-wrong'} placeholder="E-Mail" />

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.