'Using useState with if conditionals and return only two possible numbers
I'm having trouble getting this to work as I want. So basically I have an input field with a 0 prefixed. I need it to return 0 if there isn't a 1 inserted (only in that case it should return 1). But I can't change the input after I write a number and console.log doesn't return only 0 or 1. This is the code:
import { useState } from "react";
import "./App.css";
const App = () => {
const [inputValue, setInputValue] = useState('0');
const changeInputValue = (event) => {
let newInput = event.target.value === "1" ? 1 : 0;
setInputValue(newInput);
console.log(newInput);
};
return (
<div className="App">
<div>
<label for="input1">Enter 0 or 1:</label>
<input
type="number"
id="input1"
value={ inputValue }
onChange={(e) => changeInputValue(e)}
/>
</div>
</div>
);
};
export default App;
Solution 1:[1]
Check that you are using '0' as a default value not 0 and '0' is a string, either use parseInt() or remove the quotation marks also you should convert the value of the input to a number also.
I also recommend using htmlFor instead of for in your label.
Solution 2:[2]
Just change this (you initialize a string)
const App = () => { const [inputValue, setInputValue] = useState('0');
By this
const App = () => { const [inputValue, setInputValue] = useState(0);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | killerdroid99 |
| Solution 2 | DADA5000 |
