Reputation: 67
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.
Upvotes: 1
Views: 605
Reputation: 693
This could be due to variable type. Force typecast. example: +'0'
gets you 0
.
You can rather try writing as: disabled={Boolean(+number)}
Upvotes: 3
Reputation: 810
<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
Upvotes: 1