2
votes

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.

7
use parseInt function - tarzen chugh
Why you are not accepting any answer? Is there anything wrong or missing in my answer (stackoverflow.com/a/68177209/12247829)? - Rohit Nishad

7 Answers

5
votes

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 });
5
votes

Actually there is a more direct way. You can simply get the value as a number without transforming it :

event.target.valueAsNumber

1
votes

Why this error?

$event.target.value will always a string or undefined (or the empty string in the case that value is undefined).

Solution:

You have two solutions, neither use the other property of $event.target nor convert this string to a number.

Solution 1: (I highly recommend)

console.log(typeof $event.target.valueAsNumber) // Use valueAsNumber instead of value

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

Extra: $event.target.value is only avialbe for input type element. For example, if I click a div then $event.target is a div that does not have value.

0
votes

You can do this by parsing the string to an integer:

this.setState({data: parseInt(event.target.value, 10) });
0
votes

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)

0
votes

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

0
votes
function changeHandler(event: any) {
        let { name, valueAsNumber, value } = event.target;
        setStateVariable((prevState: stateVariableInterface| undefined) => ({
          ...prevState,
          [name]: Number.isNaN(valueAsNumber) ? value : valueAsNumber,
        }));
      }