Mark As Completed Discussion

Forms and Controlled Components

In React, forms are an essential part of building interactive user interfaces. They allow users to enter and submit data.

When working with forms in React, it is recommended to use controlled components. Controlled components are components whose values are controlled by React state.

To create a controlled component, you need to handle the onChange event of the input element and update the corresponding state variable.

Here's an example of a controlled input component:

SNIPPET
1import React, { useState } from 'react';
2
3function Form() {
4  const [name, setName] = useState('');
5
6  const handleInputChange = (event) => {
7    setName(event.target.value);
8  };
9
10  return (
11    <form>
12      <label>
13        Name:
14        <input type="text" value={name} onChange={handleInputChange} />
15      </label>
16      <button type="submit">Submit</button>
17    </form>
18  );
19}
20
21export default Form;

In the above example, an input element is rendered with the value attribute set to the name state variable. The handleInputChange function updates the name state variable whenever the input value changes.

By using controlled components, you have full control over the form data. You can perform validation, handle form submission, and update the state accordingly.

Remember to always provide the value attribute and the onChange event handler when working with form inputs in React. This ensures that the state and the UI are always in sync.

Let's practice what we've learned so far by creating a simple form with a controlled component.

Your Task:

Create a form component that has an input field for the user's name and a button to submit the form. When the form is submitted, display an alert with the user's name.

Once you have completed the task, click the Next button to continue.

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