React Controlled vs Uncontrolled Elements
The Difference Between Controlled and Uncontrolled Elements
Uncontrolled Element
The main difference between a controlled and uncontrolled element is where the current value of the input is being stored. In an uncontrolled element the value is being stored inside of the HTML input, in the DOM. In a controlled element the value is being stored inside of the React Component.
Let us take a look at a simple refactor for a text input to change it from an uncontrolled, to a controlled element.
class SearchBar extends React.Component {
render() {
return (
<div className="ui segment">
<form className="ui form">
<div className="field">
<label>Image Search: </label>
<input type="text" onChange={(e) => console.log(e.target.value)} />
</div>
</form>
</div>
);
}
}
Controlled Element
In the above example the value of the input is living inside of the DOM element. In the below example we have initialized a state, set the value of the state to the value of the element every time the element is changed, and then made the value of the element equal to the value of the state.
class SearchBar extends React.Component {
// here we decide what to do with those changes
state = { term: "" };
render() {
return (
<div className="ui segment">
<form className="ui form">
<div className="field">
<label>Image Search: </label>
<input
type="text"
value={this.state.term}
onChange={(e) => this.setState({ term: e.target.value })}
/>
</div>
</form>
</div>
);
}
}
In this way the value of the element is being tracked by the component, and the displayed value is coming from the state of the component. IE “Controlled”.
Having a controlled component makes it very easy to manipulate the value that is shown in the input. For example, if we wanted to make all the text uppercase, it is easy to manipulate the input as it is recycled back into the DOM with every keystroke.
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.