Last updated: Apr 7, 2024
Reading timeยท3 min
To set a default value for an input element in React:
useState
hook for controlled
fields.defaultValue
prop on uncontrolled input fields.import {useRef, useState} from 'react'; export default function App() { const [firstName, setFirstName] = useState('Default value'); const ref = useRef(null); const handleClick = () => { console.log(ref.current.value); }; return ( <div> {/* ๐ For a controlled input field */} <input value={firstName} onChange={event => setFirstName(event.target.value)} /> {/* ๐๏ธ For a controlled input field */} <input ref={ref} defaultValue="My default value" /> <button onClick={handleClick}>Click</button> </div> ); }
The code sample shows how to set a default value for controlled and uncontrolled input fields.
When working with a controlled input field, we pass the default value to the useState hook.
const [firstName, setFirstName] = useState('Default value');
The useState
hook takes the initial state as a parameter, so the firstName
state variable will get initialized to Default value
.
defaultValue
prop on a controlled input field because setting both value
and defaultValue
props is not allowed.I've also written a tutorial on how to set a conditional initial value for useState.
To set a default value for an uncontrolled input field, set the defaultValue
prop on the field.
import {useRef} from 'react'; export default function App() { const ref = useRef(null); const handleClick = () => { console.log(ref.current.value); }; return ( <div> {/* ๐๏ธ for a controlled input field */} <input ref={ref} defaultValue="My default value" /> <button onClick={handleClick}>Click</button> </div> ); }
Notice that we aren't setting the value
or onChange
props on the
uncontrolled input field.
<input ref={ref} defaultValue="My default value" />
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 a guide on how to set an input field's value using a Ref.
You can learn more about the related topics by checking out the following tutorials: