Setting a default value for an Input element in React

avatar

Borislav Hadzhiev

Last updated: Apr 30, 2022

banner

Photo from Unsplash

Setting a default value for an Input element in React #

To set a default value for an input element in React:

  1. Pass the default value as a parameter to the useState hook for controlled fields.
  2. Set the defaultValue prop on uncontrolled input fields.
App.js
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> ); }

set default value for input

The code snippet 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.

App.js
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.

Make sure you aren't setting the defaultValue prop on a controlled input field because setting both value and defaultValue props is not allowed.

To set a default value for an uncontrolled input field, set the defaultValue prop on the field.

App.js
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.

You can pass an initial value to an uncontrolled input with the 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 wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.