MomasVII
MomasVII

Reputation: 5071

Add multiple classes in if statements in React

I'm trying to conditionally add a few classes in React like this....

<div
  className={`timesContainer ${
    index === selectedItemId && selectedItemState ? 'active' : ''
    this.checkwidth(slotRow.availableSlots) ? 'responsiveTimes' : ''
  }`}
>

But obviously you can't do this multiple times. Any succinct way to do this?

Thanks

Upvotes: 0

Views: 1179

Answers (2)

Suraj Sharma
Suraj Sharma

Reputation: 857

I would recommend using clsx a light weight npm library to conditionally add multiple classnames.

Using complex ternary operators in the template literal can make your code less readable.

clsx Example

import clsx from 'clsx';

const classNames = clsx('timesContainer',{
'active': index === selectedItemId && selectedItemState,
'responsiveTimes': this.checkwidth(slotRow.availableSlots)
}

return (<div className={classNames} />

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370759

Use multiple ${}s to interpolate. Make sure to put a space between the } and the ${ next to it.

<div
  className={`timesContainer ${
    index === selectedItemId && selectedItemState ? 'active' : ''
  } ${
    this.checkwidth(slotRow.availableSlots) ? 'responsiveTimes' : ''
  }`}
>

You also might consider defining the class name ahead of time, it might be easier to read in some situations.

const className = `timesContainer ${
  index === selectedItemId && selectedItemState ? 'active' : ''
} ${
  this.checkwidth(slotRow.availableSlots) ? 'responsiveTimes' : ''
}`;

// ...

<div
  className={className}
>

Upvotes: 2

Related Questions