Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What value do you use for initializing state variable of type number in React?

Let's say, I have a state variable called amount and I have an input field which changes the variable when we type in it. I don't want to show the initial value as 0. With what should I initialize the state variable then? I tried initializing with null but console threw a warning:

Warning: 'value' prop on 'input' should not be null.
Consider using the empty string to clear the component or 'undefined' for uncontrolled components.

I've two questions now:-

  1. Why input field throws a warning when it receives a value as null? I tried googling but was not able to get a clear answer.
  2. With what should I initialize number type state variables?
like image 707
ShadowLeaf Avatar asked Dec 11 '25 00:12

ShadowLeaf


1 Answers

Let me answer both your questions one by one:

1. Why input field throws a warning when it receives value as null?

This warning is shown because React expects the value prop of a controlled input component to be a string, number (or undefined if input type is uncontrolled1). When the value is set to null, React considers it as an incorrect value type, so it throws a warning to remind you to use an appropriate value type.

Key point to note from the official docs:2

The value you pass to controlled components should not be undefined or null.

2. With what should I initialize number type state variables?

If you don't want to show an initial value of 0, you can initialize the state variable with an empty string (''). This way, the input field will appear empty initially, and React won't throw a warning that you're getting. This is also inferred from the official docs2 which says:

If you need the initial value to be empty (such as with the firstName field below), initialize your state variable to an empty string ('').

const [amount, setAmount] = useState('');

  const handleChange = (e) => {
    // do whatever you want with amount by parsing it to number
    setAmount(e.target.value);
  };
...
<input type="number" value={amount} onChange={handleChange} />

Demo here


References and further reading:

  1. Controlled and Uncontrolled components in React

  2. Controlling an input with a state variable

  3. Converting a string to number in Javascript

like image 69
mandy8055 Avatar answered Dec 13 '25 13:12

mandy8055