Dylan Bozarth
Dylan Bozarth

Reputation: 1704

Having an active state toggler on multiple buttons

I am trying to have my buttons light up once clicked, and dim when clicked twice. To indicate the user has already clicked that button.

 const [isActive, setActive] = useState("false");
const handleToggle = () => {
  setActive(!isActive);
};

And my buttons are toggling with the following code

<button
            type="button"
            value="Peperoni, "
            className={isActive ? "button btn first" : "button btn firstActive"}
            onClick={(event) => {
              ToppingPlusMinus(event);
            }}
          >
            Pepperoni
          </button>

So far I have this working, however the buttons are all tied to the same state so when one is clicked they all light up. I am stumped on how to downsize this and make each button toggle its active class individually.
I'm aware I could just brute force it with many states for each button, but I know there is a smarter solution on there.
Thank you in advance for your time. My full code is on a codesandbox here

Upvotes: 0

Views: 50

Answers (1)

uke
uke

Reputation: 891

You need to create a component that tracks its own state and fires the onClick

const ButtonClickable = props => {
 const [isActive, setActive] = useState(false);
 const handleToggle = (ev) => {
  setActive(!isActive);
  props.onClick && props.onClick(props.value)
 };
  return <button
            type="button"
            className={isActive ? "button btn first" : "button btn firstActive"}
            onClick={handleToggle}
          >
            {props.value}
          </button>

}

Then in the parent compoennt


<ButtonClickable onClick={ToppingPlusMinus} value="Peperoni, "/>
<ButtonClickable onClick={ToppingPlusMinus} value="Other, "/>
<ButtonClickable onClick={ToppingPlusMinus} value="Milk, "/>

Note that ToppingPlusMinus becomes ToppingPlusMinus(value)

Upvotes: 1

Related Questions