What are controlled inputs with React?

Some introduction

The official documentation defines controlled inputs as:

The React component that renders an element also controls what happens in that element on subsequent user input. An input form element whose value is controlled by React in this way is called a “controlled input.”

Two building blocks

Two different concepts are important to make controlled inputs work:

  • Component state
  • onChange methods

To change the properties of React components, the creation of a new component object to replace the original is necessary.

Working mechanism

To make a controlled text input, we add two properties to the input element:

  • The first is its value, which ties the contents of that input element to the component’s state,this.state.input, as shown in lines 4 and 21 of the snippet below.

  • The second is the onChange method, shown in line 21, that will get called whenever the browser needs to update that input element.

The method, indicated by lines 12-14, to handle the update, updateHandle, takes an argument, often called event (or just e) by convention. The event contains information about what changed. In-text inputs, event.target.value holds the input element’s new string. This is likely the old string with the newly typed character appended.

class App extends Component {
constructor(props) {
super(props);
this.state = {input : ''};
this.logIt = this.logIt.bind(this);
this.updateHandle = this.updateHandle.bind(this);
}
logIt(event) {
event.preventDefault();
console.log('submit button clicked for user '+ this.state.input);
}
updateHandle(event) {
this.setState({input: event.target.value});
}
render() {
return (
<div>
<h1>Registration Form</h1>
<form>
Username&nbsp;
<input type="text" value={this.state.input} onChange={this.updateHandle}/>
<br/>
<button onClick={this.logIt}>Register</button>
</form>
</div>
);
}
}
export default App;

Benefits of using controlled inputs

The most prominent benefit of controlled inputs is their ability to react to updated inputs. It is common for validating different types of inputs, such as:

  • Showing password strength
  • Validating the format of an email or a phone number
  • Auto-completion suggestions

Different input types

In summary, the different inputs use different properties to determine what is displayed, what gets called when the input is updated, and how the method can access the input. The following is the summary of the most common input types.

Controlled Input Types
Controlled Input Types

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved