If you start learning React, soon enough you’ll encounter concept called controlled inputs. This is also closely tied with the topic of event handlers. In this article, I want to discuss both these concepts in React and why they are so important to development.
In short, controlled inputs are text fields, checkboxes, dropdowns, and other input elements that get their value from the state. Normal thing in plain HTML is for input elements to have their own state. In React, value attribute is set to state values to better ‘control’ input values, ensure consistency and make certain tasks like validation a little easier to perform.
For example, to do a basic form validation, you may have to access uncontrolled components and evaluate their current value. That process still might not work. With controlled components, you can simply access value stored in an object or a variable.
Now, let’s talk about event handling in React. Event handlers are functions that run when a certain event occurs.
Event handlers are especially important for controlled components. Without them, the entire concept doesn’t work. Event handlers are necessary to update the state whenever user changes their input. So the onChange event handler usually accesses current value in the input fields and uses the function returned by useState to update state values.
Event handlers like onClick are also useful to override default browser behaviors. For example, prevent reloading the page after submit, or set onClick on link component to perform an action in addition to default navigation. Learn more about that in this guide.
Input elements need to get their value from the state. To do this, you need to set their value attribute to a state value. This attribute specifies where input element’s value comes from. This creates a type of two-way binding, where input elements get their value from the state, and also changes in the input update the state.
Technically, you can set the value attribute to anything – from strings to integers. However, then input element value will be fixed and users won’t be able to change it.
Event handlers in React receive one argument that stands for SyntheticEvent. This is a useful object that contains information about the event and the element that triggered the event.
In the function definition, developers use e or event to stand for SyntheticEvent. You can access current user’s input on e.target.value.
Understanding of controlled inputs and event handlers is the key to becoming a good React developers. It is absolutely necessary to create smart forms and implement a number of useful features like dynamic validation and autocomplete.