ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Friday, November 18, 2022

[FIXED] How do I avoid getting a NAN error when cleaning a React Input field type number?

 November 18, 2022     nan, react-hooks, reactjs, state, typescript   

Issue

I have an application where i have a input type number fields with a state.

When the user erases all the characters it gives a NaN error.

What solution to avoid the error when the user empties the price field?

I've tried the following solution below, but when it gets an empty number field, it returns a 0, but unfortanely when the user start typing again the 0 keeps on the left side....

 const changePresupuestoObraInput = (e: ChangeEvent<HTMLInputElement>) => {

    //here i transform the empty NAN value into a 0
   if(isNaN(parseFloat(e.target.value))){
      const number = Number(e.target.value);
      setEditInputPresupuestoObra(number)
   };

   //here i parse the e.target.value and set on my state
   if(!isNaN(parseFloat(e.target.value))){
    const number = parseFloat(e.target.value)
    setEditInputPresupuestoObra(number)
 };
    
 //here i update my obra.
    if (obraInfo) {
      setObraInfo({ id: obraInfo.id, name: obraInfo.name, direccion: obraInfo.direccion, presupuesto: editInputPresupuestoObra })
    }
  }

below the code of my input:

<input type="number" readOnly={readOnlyBoolean} value={editInputPresupuestoObra} onChange={changePresupuestoObraInput} name="presupuestoObra" />

I've searched a lot about NaN but didn't find about this. Any suggestion ?


Solution

after searching i could find a solution:

let number = parseInt(e.target.value) || "";

Below i'll put all the code:

const changePresupuestoObraInput = (e: ChangeEvent<HTMLInputElement>) => {

let number = parseInt(e.target.value) || "";

  setEditInputPresupuestoObra(number as number);

//here i update my obra.
if (obraInfo) {
  setObraInfo({ id: obraInfo.id, name: obraInfo.name, direccion: obraInfo.direccion, presupuesto: editInputPresupuestoObra })
}

}

<input type="number" readOnly={readOnlyBoolean} value={editInputPresupuestoObra} onChange={changePresupuestoObraInput} name="presupuestoObra" />

Doing this way solved the problem and it doesnt show console NaN error anymore. Hope it helps somebody.



Answered By - Breno Santin
Answer Checked By - - Willingham (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix