bradrar
bradrar

Reputation: 737

Make counter not be less than zero in React.js

Consider the following code :

import React, { Component } from 'react';

class Counter extends Component {
  state = { value: 5 };

  increment = () => {
    this.setState(prevState => ({
      value: prevState.value + 1
    }));
  };

  decrement = () => {
    this.setState(prevState => ({
      value: prevState.value - 1
    }));
  };

  render() {
    return (
      <div>
        {this.state.value}
        <button onClick={this.increment}>+</button>
        <button onClick={this.decrement}>-</button>
      </div>
    )
  }
}

How can I make it so that whenever I click the Decrement button, the value will not be less than 0. The value's minimum will always be zero and not -1, -2 ,-3 ,-4 ...

Upvotes: 0

Views: 3363

Answers (4)

NimaDoustdar
NimaDoustdar

Reputation: 326

On Way Use Conditional (ternary) operator in decrement Function

     decrement = () => {
        this.setState(prevState => ({
          value: prevState.value ? prevState.value -1 : 0
        }));
      };

Upvotes: 0

Yedu Krishnan S M
Yedu Krishnan S M

Reputation: 21

you can test it

 const onPressDecrement = () => setCount((prevCount) => (Math.max(prevCount - 1,1)));

Upvotes: 0

Mile Mijatović
Mile Mijatović

Reputation: 3177

That's how number input works. To simplify the code you could try to use validity state (if your target browsers support it)

onChange(e) {
    if (!e.target.validity.badInput) {
        this.setState(Number(e.target.value))
    }
}

Example

Upvotes: 0

Bluefire
Bluefire

Reputation: 14099

Just set a minimum value in your decrementing code:

decrement = () => {
  this.setState(prevState => ({
    value: Math.max(prevState.value - 1, 0)
  }));
};

Upvotes: 4

Related Questions