How to set default values for uncontrolled React components

In React, the value attribute on form elements will override the value in the DOM. With an uncontrolled component, you might want React to specify the initial value, but leave subsequent updates uncontrolled. To handle this case, you can specify a defaultValue attribute instead of value prop.

render() {
return (
<form onSubmit={this.handleSubmit}>
User Name:
ref={this.input} />
<input type="submit" value="Submit" />

The same applies for select and textArea inputs. But you need to use defaultChecked for checkbox and radio components.

It's important to note that setting a default value like this only applies when the component is first rendered. If the user enters a new value into the field, the default value will be overwritten.

April 11, 2022