Course contentsShow
← React
Lesson 487 of 2,39613. Controlled ComponentsFree lesson

Number Input: Parsing and Validation

Parse e.target.value with Number() or parseInt() and handle empty strings appropriately.

Number Input: Parsing and Validation

You'll learn how to properly handle number inputs by converting strings to numbers and managing empty input states.

The Core Problem

When you use an <input type="number"> with a controlled component pattern, React still gives you event.target.value as a string, not a number. If you store "42" (string) in state instead of 42 (number), you'll run into bugs when performing calculations or comparisons.

Parsing the Value

Use Number() or parseInt() to convert the string:

const [age, setAge] = useState(0);

function handleChange(event) {
  const value = event.target.value;
  setAge(Number(value));  // converts "42" → 42
}

The Empty String Problem

When the user clears the input, event.target.value becomes "" (empty string). Number("") evaluates to 0, which might not be what you want. Handle this explicitly:

function handleChange(event) {
  const value = event.target.value;
  
  if (value === '') {
    setAge('');  // allow empty state
  } else {
    setAge(Number(value));
  }
}

Or use parseInt() for integers, which returns NaN for empty strings (you can check with isNaN()).

Why This Matters

Think of it like a calculator display: when you type "5", the calculator needs to know that's the number 5, not the character "5", so it can perform math. Similarly, React needs you to explicitly convert input strings into numbers for your application logic to work correctly.

Key Takeaway: Always parse event.target.value with Number() or parseInt() for number inputs, and handle the empty string case explicitly to avoid unexpected 0 values or NaN errors.