Mandalina
Mandalina

Reputation: 446

ReactJS - onClick change text of clicked buttons

I have a screen with multiple buttons, and when one is clicked I want to change the text of the clicked button for 5 seconds. I basically have something like this. But I only want the clicked button text to change. Any help would be appreciated!

handleClick = () => {

      this.setState({
        buttonText: "Added"
      });

      setTimeout(() => {
        this.setState({
          buttonText: "Add To List"
        });
      }, 5000)
}

render () {
 return(
  <React.Fragment>
    <button onClick={this.handleClick}>{this.state.buttonText}</button>
    <button onClick={this.handleClick}>{this.state.buttonText}</button>
    <button onClick={this.handleClick}>{this.state.buttonText}</button>
  </React.Fragment>
 )
}

Upvotes: 0

Views: 99

Answers (1)

Whotriesout Theon
Whotriesout Theon

Reputation: 150

Just put this logic into a component and use it 3 times, so each component has it's own state and not a shared one.

This is how the component would look like

export class Button {
  handleClick = () => {

      this.setState({
        buttonText: "Added"
      });

      setTimeout(() => {
        this.setState({
          buttonText: "Add To List"
        });
      }, 5000)
  }

  render () {
   return(
     <button onClick={this.handleClick}>{this.state.buttonText}</button>
   )
  }
}

And in your main component you could use it like this

render () {
 return(
  <React.Fragment>
    <Button />
    <Button />
    <Button />
  </React.Fragment>
 )
}

Upvotes: 7

Related Questions