Understanding Controlled Components
Explore how controlled components work in React by learning to synchronize input values with component state. Understand how to implement change handlers to update state, making form inputs interactive. This lesson guides you through converting an input into a controlled component and managing form submission events for better user input handling.
We'll cover the following...
In this section, we are going to learn how to use what are called controlled components to implement a form. A controlled component has its value synchronized with the state in React. This will make more sense when we’ve implemented our first controlled component.
Changing our app header to a controlled component
Let’s open our project in Visual Studio Code and change the search box in our app header to a controlled component. Follow these steps:
Open
Header.tsxand add the following imports:
The default value for the search box is going to be the
criteriaroute query parameter. So, let’s use theuseSearchParamshook from React Router to get this: ...