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:-
null? I tried googling but was not able to get a clear answer.Let me answer both your questions one by one:
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.
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
Controlled and Uncontrolled components in React
Controlling an input with a state variable
Converting a string to number in Javascript
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With