0

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

2 Answers 2

2

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

Comments

0

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} />

1 Comment

Here's a blog post link If you're interested in reading more about conditionally adding classnames in react using clsx

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.