0

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 }
      ],
    };
  }
Xwind
  • 71
  • 5
  • Check out this question: https://stackoverflow.com/questions/49477547/setstate-of-an-array-of-objects-in-react – Enfield Li May 19 '22 at 03:42

1 Answers1

0
this.state = {
      buttons: [
        { id: 'button1', title: "Button 1", pressed: false, timePress : null },
        { id: 'button2', title: "Button 2", pressed: false, timePress : null },
        { id: 'button3', title: "Button 3", pressed: false, timePress : null }
      ],
    };

handlePressButton (button,index) {
    this.state.buttons[index].pressed = true
    this.state.buttons[index].timePress= Date.now() //or new Date()
    this.setState({
        buttons : [...this.state.buttons ]
    })

}

render () {
   return (
      <>
      this.state.buttons.map(button => <div> Pressed at : {button.timePress || "not yet"} </div> )
      this.state.buttons.map((button , index) => <Button onClick={() =>this.handlePressButton(button,index)} > {button.title} </Button> )

</>

   )
}

Phạm Vỹ
  • 130
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 19 '22 at 16:57