3

I have made 2 buttons one for increment and another for decrement. When I click on minus button it should not display negative values but in my case when I click on minus button (initially value zero ) it shows -1 and again on click it shows zero why is this happening when I click on minus button the value inside the input box should not get decremented below 0.

datepicker.js :

import React, { Component } from 'react';
import './datepicker.css';

class DatePicker extends Component {

  constructor(props){
    super(props);
     this.state = {
        counter:0
     };
   }

  increment(){
    this.setState({
      counter: this.state.counter + 1
    });
  }

  decrement(){
      if(this.state.counter < 0){
        this.setState({
            counter:0
        });
      }else {
        this.setState({
            counter: this.state.counter - 1
        });
      }
  }


  render() {
    return (
      <div>
        <div id="center">
            <label for="name">Date</label>
            <p></p>
            <button type="button" className="btn btn-success" id="plus" onClick={this.increment.bind(this)}>+</button>
            <input type="text" id="date" value={this.state.counter}/>
            <button type="button" className="btn btn-danger" id="minus" onClick={this.decrement.bind(this)}>-</button> 
        </div>
      </div>
    );
  }
}

export default DatePicker;

Screenshot : In screnshot it shows -1 and now if I click it, it will show zero. I do not want to display negative values the lower bound must be 0 always. enter image description here

stone rock
  • 1,923
  • 9
  • 43
  • 72

5 Answers5

5

Why it's not working in your case?

Because you are checking the wrong condition here:

if(this.state.counter < 0){...}

It should be:

if(this.state.counter == 0){...}

Solution:

Decrement the value only when the counter value is greater than 0. Like this:

decrement(){
   if(this.state.counter > 0){
      this.setState(prevState => ({counter: prevState.counter-1}))
   }
}

Or

decrement(){
      this.setState(prevState => 
          ({counter: prevState.counter? prevState.counter-1: 0})
      )
}
Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
1

You decrement function needs to change the logic, since you are checking this.state.counter < 0 which which will be false when counter is 0, and only in the next click will it be true. Also when you are using previous state to update the next state use functional setState. Check this

When to use functional setState:

decrement(){
      if(this.state.counter === 0){
        this.setState({
            counter:0
        });
      }else {
        this.setState(prevState => ({
            counter: prevState.counter - 1
        }));
      }
  }

Working codesandbox

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

You can also uses like this.

 decrement = () =>{
    if(this.state.value< 1){
      this.setState({
        value:0
      });
    }else {
      this.setState({
        value: this.state.value- 1
      });
    }
  };
  • Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Thanks – sɐunıɔןɐqɐp Sep 13 '18 at 08:11
1

This would be the simplest approach

import React, {useState} from 'react';

function Counter(){
  const [count, setCount] = useState(0);

  const dec = () => {
    if(count <= 0) {
      return;
    } else {
      setCount(count - 1);
    }
  }

  return (
   <button onClick={dec}> - </button>
   <button onClick={setCount(count + 1)}>  + </button>
 )

}

cbh17sen
  • 11
  • 1
0

one thing you can do is use ternary operator and use check the value of count.

like this:


function Usestate() {
    const [count, setCount] = useState(0)
    return (
        <div>
            <button onClick={() => setCount(count + 1)}>Count {count}</button>
            <button onClick={() => { (count == 0) ? setCount(0) : setCount(count - 1) }}>Count {count}</button>

        </div>
    )
}
export default Usestate