1

I'm trying to have the button disabled whenever the input is equals to 0. In the beginning, the button is disabled but when I try to increase the input > 0 and decrease the input back to 0, the button won't be disabled.

constructor() {
    super();
    this.state = {
      number: 0,
    };
  }
onInputChange = (e) => {
    this.setState({ number: e.target.value });
};


  render() {
    const { number} = this.state;

    return (
      <Fragment>
        <input
          value={number}
          type="number"
          max="100"
          min="0"
          onChange={this.onInputChange}
        ></input>
        <Button
          style={{ display: "block" }}
          disabled={number === 0 ? true : false}
        >
          Print
        </Button>

Could someone explain to my why the state is changed but the disable property won't work? If I set the condition to:

  <Button
          style={{ display: "block" }}
          disabled={number < 1 ? true : false}
        >

then the code works fine. But I really want to know why my first approach doesn't work. Thank you.

JadenB
  • 57
  • 2
  • 9
  • 3
    Returned typeof value from `e.target.value` is string, you should use some like `parseint` to transform string to int – Pavel Petrovich Jul 12 '20 at 04:13
  • Great answer, thank you! Since I'm using "===", the type needs to be the same. That's why it doesn't work. – JadenB Jul 12 '20 at 04:18

2 Answers2

3

This could be due to variable type. Force typecast. example: +'0' gets you 0.

You can rather try writing as: disabled={Boolean(+number)}

Neetigya Chahar
  • 683
  • 5
  • 14
1

<input elements return a string value even if you set type as number. So comparing a string 0 with number 0 using strict equality (===) returns false. You can use == which returns true for "0" == 0

disabled={ "0" === 0} // Returns false

disabled={ "0" == 0} // Returns true

Or you can use parseInt to cast string to integer before setting state. Then you can use your first comparision.

onInputChange = (e) => {
 this.setState({ number: parseInt(e.target.value) });
};

For further reading on comparisions in js : Why does string to number comparison work in Javascript

Çağatay Sel
  • 801
  • 7
  • 14
  • That's absolutely true, my mistake was using strict comparison. Thank you for your detailed explanation. – JadenB Jul 12 '20 at 08:21