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 different concepts are important to make controlled inputs work:
state
onChange
methodsTo change the properties of React components, the creation of a new component object to replace the original is necessary.
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 <input type="text" value={this.state.input} onChange={this.updateHandle}/><br/><button onClick={this.logIt}>Register</button></form></div>);}}export default App;
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:
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.
Free Resources