Reputation: 333
I have an input field and When we enter the value in the input field I am updating the state with the entered value using event.target.value. By default the event.target.value
be a string. Can we convert that into an integer ?
const func=(props)=>{
return(
<div>
<input type="text" onChange={props.change} value={props.value}/>
</div>
)};
// handler function
changeHandler =(event)=>{
this.setState({data:event.target.value})
};
My state has integer value that i assigned to Zero (data:0). So while updating the state using changeHandler function data becomes string.I want to typecast the event.target.value to the integer.
Upvotes: 16
Views: 37114
Reputation: 536
Actually there is a more direct way. You can simply get the value as a number without transforming it :
event.target.valueAsNumber
Also for edge cases use it like const value = isNaN(e.target.valueAsNumber) ? null : e.target.valueAsNumber;
Upvotes: 44
Reputation: 2765
Solution 1: (I highly recommend)
console.log($event.target.valueAsNumber) // Use valueAsNumber instead of value
Note: $event.target.valueAsNumber
is not avilable for few input elements such as select, options etc. In that case use Solution 2.
(@Mads Hjorth)
Solution 2:
use parseInt()
or parseFloat()
or Number()
var integer = Number('613613');
// var integer = parseFloat('613613');
// var integer = parseInt('613613', radix); // radix is option parameter
Why this error?
$event.target.value
will always be a string or undefined.
$event.target.value
is only available for input type element. For example, if I click a div then $event.target
is a div that does not have value
property.
Upvotes: 7
Reputation: 89
function changeHandler(event: any) {
let { name, valueAsNumber, value } = event.target;
setStateVariable((prevState: stateVariableInterface| undefined) => ({
...prevState,
[name]: Number.isNaN(valueAsNumber) ? value : valueAsNumber,
}));
}
Upvotes: 0
Reputation: 29
I was able to do it using parseFloat(). In your case, you can try
changeHandler = event => {
this.setState({ data: parseFloat(event.target.value) });
};
But make sure to only use this handler when numbers will be added or else you get an error NaN
in state.data
Upvotes: 0
Reputation: 7492
Here is a syntactic sugar version of the other answers which will also attempt to convert your value to an int (or return NaN) in base 10
:
this.setState({data: +event.target.value });
Upvotes: 12
Reputation: 935
You can do that with parseInt
function.Documentation on this
this.setState({data: parseInt(event.target.value, X)})
Where X
is your radix (per documentation)
Upvotes: 0
Reputation: 49959
You can do this by parsing the string to an integer:
this.setState({data: parseInt(event.target.value, 10) });
Upvotes: 1