Adam Weiler
Adam Weiler

Reputation: 571

Four buttons use One Function?

I'm writing this in React.

Right now I have 2 sets of numbers which are controlled by 4 buttons; 2 increment buttons and 2 decrement buttons. The increment buttons raise each number, the decrement buttons lower each number.

I've created a function that does this for one of the decrement buttons. But I don't know how to make it dynamic based on which button is clicked. I don't want 4 separate functions, I'd prefer 2 functions or even just 1.

This is the function:

decrementClick() {
        if (this.state.breakLength > 1) {
          this.setState({ breakLength: this.state.breakLength - 1 })
        }  
    }

And this is the JSX code:

<button id="break-decrement" onClick={this.decrementClick.bind(this.decrementClick)}>▼</button>

I can pass a value from the button into the function, but how can it modify the proper state?

Upvotes: 1

Views: 103

Answers (1)

fabio.sussetto
fabio.sussetto

Reputation: 7055

Check this out:

class MyComponent extends React.Component {
  state = {
    foo: 0,
    bar: 0
  }

  handleUpdateCounter(counterId, operation, event) {
    this.setState(prevState => ({
      [counterId]: operation === 'increment' ? prevState[counterId] + 1 : prevState[counterId] - 1
    }));

  }

  render() {
    const { foo, bar } = this.state

    return (
      <div>
          Foo: {foo}, Bar: {bar}
          <button onClick={this.handleUpdateCounter.bind(this, 'foo', 'increment')}>I increment foo</button>

          <button onClick={this.handleUpdateCounter.bind(this, 'bar', 'decrement')}>I decrement bar</button>

      </div>
    )
  }

}

The trick is to use .bind() to create a new version of handleUpdateCounter with some of the arguments "fixed".

A couple of notes:

{
 [myVar]: "test"
}

is how you set a dynamic key in the object, using the key name stored in myVar as a string.

We use this.setState(callback) to make sure we read the previous value of the counter, since setState is asynchronous.

Upvotes: 2

Related Questions