I have this code below, which when I click the button, it will render the current time
But when I click again to update the new time, it will update all three at the same time. I want to update only the button I clicked
I'm guessing the problem is all three using the same state.
constructor(props) {
super(props);
this.state = {
button1: false,
button2: false,
button3: false,
};
}
onClickHandler = (type) => {
this.setState({[type]: true})
}
render() {
return (
<div>
{this.state.button1 && <div>{ this.state.curTime }</div>}
{this.state.button2 && <div>{ this.state.curTime }</div>}
{this.state.button3 && <div>{ this.state.curTime }</div>}
<div>
<Button
onClick={() => { this.getTimePress(); this.onClickHandler("button1") }}
>Button 1
</Button>
<Button
onClick={() => { this.getTimePress(); this.onClickHandler("button2") }}
>Button 2
</Button>
<Button
onClick={() => { this.getTimePress(); this.onClickHandler("button3") }}
>Button 3
</Button>
</div>
</div>
)
}
}
And I was thinking of using map()
might solve the problem, but I'm having a hard time figuring out how to modify boolean for each button.
this.state = {
buttonList: [
{ id: 'button1', title: "Button 1", pressed: false },
{ id: 'button2', title: "Button 2", pressed: false },
{ id: 'button3', title: "Button 3", pressed: false }
],
};
}