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.

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
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"/>
You just need to store a value you could use in the state (I used '1-5') and then check against that.
function RadioButtonGroup() {
const [active, setActive] = useState('');
const handleClick = (value) => () => {
setActive(value);
};
return (
<div>
<button
className={`${active === '1-5' ? 'is-active' : ''}`}
onClick={handleClick('1-5')}
>
1-5
</button>
<button
className={`${active === '6-9' ? 'is-active' : ''}`}
onClick={handleClick('6-9')}
>
6-9
</button>
</div>
);
}
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>