skip to Main Content

Let’ say, I’ve 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 initial value as 0. With what should I initialize the state variable then? I tried initializing with null but console throws 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 value as null. I tried googling but not able to get clear answer.
  2. With what should I initialize number type state variables?

2

Answers


  1. 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 uncontrolled). 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.1

    Key point to note from the docs:2

    The value you pass to controlled components should not be undefined or null. If you need the initial value to be empty (such as with the firstName field below), initialize your state variable to an empty string (”).

    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 ('') as also mentioned above. This way, the input field will appear empty initially, and React won’t throw a warning which you’re getting.

    const [amount, setAmount] = useState('');
    
      const handleChange = (e) => {
        setAmount(e.target.value);
        // do whatever you want with amount by parsing it to number or float 
      };
    ...
    <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

    Login or Signup to reply.
  2. Simply you can use '' or undefined to avoid the warnings for the empty inputs.

    0 or NaN(null) values can also be used for initialising numeric state if appropriate.

    Managing an extra isInitialised state var is second option to hide inputs until needed

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search