MeltingDog
MeltingDog

Reputation: 15404

How to add multiple dynamic styles to a React component?

I have a React component that already has a style attached to it:

    <Link onClick={handleCollapse}>
      <KeyboardArrowDownIcon className=(classes.icon) />
      Advanced Options
    </Link>

I want to add an additional class to that component when it is clicked. So I tried:

   const [collapse, setCollapse] = React.useState(false);

   const handleCollapse = () => {
     setCollapse(prevState => !prevState);
   };

    <Link onClick={handleCollapse}>
      <KeyboardArrowDownIcon
        className={clsx(
          classes.icon,
          collapse ? 'classes.iconActive' : null
        )}
      />
      Advanced Options
    </Link>

Since I am already using collapse which is a boolean I thought I could just use it to check if it's true or false.

However, the above doesn't work.

Would anyone know what I could do to get this to work?

Upvotes: 1

Views: 190

Answers (2)

DevLoverUmar
DevLoverUmar

Reputation: 13933

You can just concatinate to the className conditionally.

const [collapse, setCollapse] = React.useState(false);

const handleCollapse = () => {
 setCollapse(prevState => !prevState);
};

<Link onClick={handleCollapse}>
  <KeyboardArrowDownIcon
    className={clsx({
    [classes.icon] : true, //always apply
    [classes.iconActive] : collapse //only when collapse === true
   })}
  />
  Advanced Options
</Link>

Upvotes: 0

hangindev.com
hangindev.com

Reputation: 4873

Mistakenly quote the variable classes.iconActive, write collapse ? classes.iconActive : null or collapse && classes.iconActive instead.

Upvotes: 1

Related Questions