Last updated: Jan 16, 2023
Reading time·3 min
value
prop on input
should not be null in ReactThe warning "value
prop on input
should not be null" is caused when we set
an initial value for an input to null
or override the initial value setting it
to null
, e.g. from an empty API response.
Use a fallback value to get around this.
Here is an example of how the warning is caused.
export default function App() { // ⛔️ Warning: `value` prop on `input` should not be null. // Consider using an empty string to clear the component or `undefined` for uncontrolled components. return ( <div> <input value={null} /> </div> ); }
The issue is that we're setting the value
prop of the input
field to null
which is not allowed.
null
.To get around this, we have to make sure to never set the value
prop on the
input
to null
by
providing a fallback value.
import {useState} from 'react'; const App = () => { // 👇️ pass empty string as initial value const [message, setMessage] = useState(''); const handleChange = event => { setMessage(event.target.value); console.log(event.target.value); }; // ✅ use fallback, e.g. // value={message || ''} return ( <div> <input type="text" id="message" name="message" onChange={handleChange} value={message || ''} /> </div> ); }; export default App;
null
.This gets rid of the warning unless you are setting the state variable to null
somewhere else in your code.
We used the
logical OR (||)
operator, which returns the value to the right if the value to the left is falsy
(e.g. null
).
This helps us make sure that the value
prop of the input
field will never be
set to null
.
defaultValue
prop for uncontrolled componentsIf you use uncontrolled input fields with refs, don't set the value
prop on
the input at all, use defaultValue
instead.
import {useRef} from 'react'; const App = () => { const inputRef = useRef(null); function handleClick() { console.log(inputRef.current.value); } return ( <div> <input ref={inputRef} type="text" id="message" name="message" defaultValue="Initial value" /> <button onClick={handleClick}>Log message</button> </div> ); }; export default App;
The example uses an uncontrolled input. Notice that the input field doesn't have
an onChange
prop or value
set.
defaultValue
prop. However, this is not necessary and you can omit the prop if you don't want to set an initial value.When using uncontrolled input fields, we access the input using a ref.
Every time the user clicks on the button in the example, the value of the uncontrolled input gets logged.
You shouldn't set the value
prop on an uncontrolled input (an input field that
doesn't have an onChange
handler) because that would make the input field
immutable and you wouldn't be able to type in it.
I've also written an article on how to set an input field's value using a ref.