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 :-
- Why input field throws a warning when it receives value as null. I tried googling but not able to get clear answer.
- With what should I initialize number type state variables?
2
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 astring
,number
(orundefined
if input type is uncontrolled). When the value is set tonull
, React considers it as an incorrect value type, so it throws a warning to remind you to use an appropriate value type.1Key point to note from the docs:2
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, andReact
won’t throw a warning which you’re getting.Demo here
References and further reading:
Controlled and Uncontrolled components in React
Controlling an input with a state variable
Converting a string to number in Javascript
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