Mark As Completed Discussion

Forms and Controlled Components

Handling form input and managing the state of controlled components in React is an essential skill for building interactive user interfaces.

Controlled Components

In React, a controlled component is a form element whose value is controlled by React. The value of the component is stored in the component's state and is updated through event handlers.

Here's an example of a controlled input component:

JAVASCRIPT
1// Define a state to hold the input value
2const [inputValue, setInputValue] = useState('');
3
4// Define an event handler to handle input changes
5const handleInputChange = (event) => {
6  setInputValue(event.target.value);
7};
8
9// Render the input element
10return (
11  <input type="text" value={inputValue} onChange={handleInputChange} />
12);

In the example above, we use the useState hook to define a state variable inputValue that holds the current value of the input field. We also define an event handler handleInputChange that updates the state inputValue whenever the input value changes.

By setting the value prop of the input element to inputValue and assigning the onChange event handler to handleInputChange, we have created a controlled input component.

Benefits of Controlled Components

Controlled components offer several benefits:

  • Single Source of Truth: The component's value is stored in the component's state, making it the single source of truth for the component's data.

  • Consistent Behavior: Since the value of the component is controlled by React, you can ensure consistent behavior by enforcing validation rules and preventing invalid input.

  • Easy State Management: By managing the component's state, you have full control over its behavior and can easily handle updates, validations, and error handling.

  • Access to Input Value: Since the value of the input is stored in state, you can access it at any time and use it in other parts of your application.

Exercise

Implement a controlled form component that takes a username and password as input fields. Store the values in state and log them when the form is submitted.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment