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
CodePudding user response:
const initialState = {
btnA: false,
btnB: false,
btnC: false,
};
const [tickets, setTickets] = useState({ ...initialState });
const handleChange = (event: React.MouseEvent<HTMLButtonElement>) => {
const { name } = event.currentTarget;
setTickets({ ...initialState, [name]: true });
};
<button name="btnA" onClick={handleChange}>button A</button>
<button name="btnB" onClick={handleChange}>button B</button>
<button name="btnC" onClick={handleChange}>button C</button>
Preview
There must be a better way. I'm cheering you on.