'How to Manipulate Sets of Buttons in React with UseStates?

Hi I am new to react and trying to get buttons to light up when you press them, however they are in sets of buttons and I'd like the other buttons in the set to not also light up when one is pressed.

Currently I used UseState() and it just turns all buttons on and off. What's the best practice work around to this, because creating 30 individual button functions does not seem practical. Buttons

  const [ticket, setTicket]=useState(false)


  const ticketHandler = () => {
    setTicket (!ticket);
  }
  <button onClick={ticketHandler} className={`${ticket? 'is-success': ''} button`}>1-5</button>
  <button onClick={ticketHandler} className={`${ticket? 'is-success': ''} button`}>6-9</button>

in this example both ticket '1-5' and ticket '6-9' light up green



Solution 1:[1]

You should create a separate Button component and keep the light-up logic in it. That will solve your issue.

const Button = ({ buttonText }) => {
  const [ticket, setTicket] = useState(false);

  const ticketHandler = () => {
    setTicket(!ticket);
  };

  return (
    <button
      onClick={ticketHandler}
      className={`${ticket ? "is-success" : ""} button`}
    >
      {buttonText}
    </button>
  );
};

And create buttons like this:

<Button buttonText="1-5"/>
<Button buttonText="6-9"/>

Solution 2:[2]

I would suggest to give a value to your button and pass it into your handler.

And assign the value to the ticket instead of making the ticket a Boolean

So,

const ticketHandler = (element) => {
    setTicket(element.value);

      };

const getClass = (condition) => ticket === condition ? 'is-success': ''

Button:

<button onClick={ticketHandler} value ="oneToFive" className={`${getClass("oneToFive")} button`}>1-5</button>
<button onClick={ticketHandler} value="sixToNine" className={`${getClass("sixToNine")} button`}>6-9</button>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amila Senadheera
Solution 2 Cotldus