ousmane784
ousmane784

Reputation: 446

React conditionally apply color to component

I am trying to apply a color to a div conditionally based on 4 conditions. I usually use the ternary operator in the className prop but there is 4 conditions and there has got to be a better way to do this.

For example ,

<div className={`${styles.card} ${items.length > 1 && styles.blue} ${items.length > 2 && styles.green}` etc...}>data</div>

I cant use any other libraries either its just got to be using react

Upvotes: 0

Views: 526

Answers (3)

Black Hole
Black Hole

Reputation: 1382

Maybe a method that return the styles

const Card = () => {
   const handleStyles = () => {
      const classNames = [styles.card];
      if (items.length === 1) {
        classNames.push(styles.blue);
      }
      else if (items.length > 1) {
        classNames.push(styles.green);
      }

      return classNames.join('');
   }


  return (
    <div className={handleStyles}>data</div>
  )
};

Upvotes: 0

anticol
anticol

Reputation: 647

I would use classcat package. For me is the best approach to combine multiple class names based on different conditions.

import cc from "classcat";

<div
     className={cc([
       {
         [styles.card]: true,
         [styles.blue]: items.length > 1,
         [styles.green]: items.length > 2,
       },
     ])}
>
   data
</div>

Upvotes: 0

Dean James
Dean James

Reputation: 2623

You could build an array up with classes conditionally:

const Card = () => {
  const classNames = [styles.card];
  if (items.length === 1) {
    classNames.push(styles.blue);
  } else if (items.length > 1) {
    classNames.push(styles.green);
  }

  return (
    <div className={classNames.join(' ')}>data</div>
  )
};

Edit: Modified conditions to make more sense.

Upvotes: 1

Related Questions