Introduction to Controlled Inputs
Learn what controlled inputs are and how to use them.
We'll cover the following
Two different concepts are important to making controlled inputs work: the component state and onChange
methods. To change the properties of React components, the creation of a new component object to replace the original is necessary. It minimizes the places where the application state may reside. Of course, it has its limits. If every component is unchangeable, we have a static page rather than a dynamic web application. Therefore, the state must change somewhere.
Methods of rendering the change
Controlled inputs handle the common case of user inputs by having the component manage the input’s state. This keeps the state self-contained. The information is then passed up through the component hierarchy with a callback
function. 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 state of the component, here called
this.state.username
. -
The second is the
onChange
method, which will get called whenever the browser needs to update that input element.
The method to handle the update is called updateUsername
and takes an argument, often called event
or simply e
. The event
contains information about what changed. In text the inputs, event.target.value
holds the input element’s new string. This is likely the old string with the newly typed character appended, but it could be significantly different if the user is cutting and pasting.
The onChange
method, like the logIt
method, must be bound within the constructor. The initial state for username
must be set since this.state.username
is used in the render
. It’s essential that the state is only updated directly in a constructor. After that, we must use the setState
method to ensure that what shows in the browser remains consistent with the state.
We’ve stripped down the example only to have the username input and register button. We have also updated the logIt
method to write the username state information to the console. We’d typically act on the information within the state in the submit button’s onClick
method. For example, we could send the information to the server and update the global state according to its response.
Try it yourself
-
Click the “Run” button to start the App.
-
Once it’s running, click the link inside the “Output” tab, open inspect, and then go to the console tab.
-
Here, the console should show the output from pushing the “Register” button. The output should contain the username that has been typed in.
Get hands-on with 1400+ tech skills courses.