Mark As Completed Discussion

Forms and Input Handling

In a React application, forms allow users to input data and submit it. In this section, we'll explore how to create forms and manage user input in React.

To create a form in React, you can use the form element and various input components, such as input, textarea, and select. Each input component can have its own state to manage the user's input.

Let's consider an example where we have a form with an input field for the user's name. We want to display an alert with the user's name when they submit the form:

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

In this example, we use the useState hook to create a name state variable with an initial value of an empty string. The value prop of the input component is set to this state variable, and we update the state when the user types in the input field.

When the form is submitted, the handleSubmit function is called. We prevent the default form submission behavior using e.preventDefault(), and then display an alert with the user's name.

By managing the form state and handling user input, we can create interactive forms in React.

Now it's your turn to practice! Create a form with an input field for email and a password field. Log the email and password to the console when the form is submitted.

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