'event.target.value as a number?
const [data, Setdata] = useState<number[] >([]);
const [inputData, SetinputData] = useState<number>(0);
const [canAdd, SetcanAdd] = useState<boolean>(true);
const numberField = (event: React.ChangeEvent<HTMLInputElement>) => {
SetcanAdd(false)
SetinputData(event.target.value);
if(data.includes(event.target.value)){
SetcanAdd(true)
}
// event.target.value Argument of type string is not assignable to parameter of type number
};
//jsx
<input
onChange={numberField }
placeholder="add numbers"
type="number"
value={inputData}
/>
How can I set the event.target.value
to be a number?
I know I can set everything to string, but I want it to be a number
Solution 1:[1]
Changed event.target.value to event.target.valueAsNumber.
Works now!
Edit: Lol, the answer was in my title
Solution 2:[2]
In JS, it won't be a number, even if the input is of type="number"
:
const val = document.querySelector('input').value;
console.log(typeof val);
console.log(val);
<input type="number" value=80>
So you shouldn't try to have event.target.value
be typed as a number, because it isn't.
You'll have to convert it to a number yourself explicitly, if that's what you want.
const numValue = Number(event.target.value);
// use numValue
Solution 3:[3]
you can try:
event.target.valueAsNumber
+event.target.value
Number(event.target.value)
parseInt(event.target.value) || parseFloat(event.target.value)
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 | bacco2 |
Solution 2 | CertainPerformance |
Solution 3 | Alvin Flores Acosta |