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.
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 });
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With