0

I changed my file Order.css to Order.module.css. And now I need to transform this condition from

const firstNameClass = firstNameInputHasError ? 'form-control invalid' : 'form-control'; ... <div className={firstNameClass}> ... </div> 

in something like this

 const firstNameClass = firstNameInputHasError ? classes['form-control'] + classes['invalid'] : classes['form-control']; 

first-line works fine when the name of the file is Order.css. The second line doesn't work.


Updated. Thanks to chenc that recommended classnames package


My solution

import classes from './Order.module.css'; import classNames from "classnames/bind"; let classNameBound = classNames.bind(classes); const firstNameClass = classNameBound( classes["form-control"], {invalid: firstNameInputHasError} ); 

Second solution without classnames package

const firstNameClass = `${classes["form-control"]} ${firstNameInputHasError ? classes.invalid : ''}`; 
1
  • The second line doesn't work how? Commented Sep 8, 2021 at 2:16

2 Answers 2

2

why not use classnames ? This is a good package for judging conditions to use class

Sign up to request clarification or add additional context in comments.

1 Comment

Would look lie this, className={classNames(classes['form-control'], { classes['invalid']: firstNameInputHasError })}>
1

It should be in a function, and you don't need to use a +:

const firstNameClass = firstNameInputHasError ? classes(["form-control invalid"]) : classes(["form-control"]); 

Or in short:

const firstNameClass = classes(["form-control", { 'invalid': firstNameInputHasError } ]); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.