Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type of event.target.value should be changed to integer in react

Tags:

javascript

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.

like image 296
Dharmendra Makineni Avatar asked Nov 28 '22 13:11

Dharmendra Makineni


2 Answers

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 });
like image 34
Treycos Avatar answered Dec 01 '22 03:12

Treycos


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;

like image 66
Burak Gündüz Avatar answered Dec 01 '22 01:12

Burak Gündüz