Forms and User Input
When building web applications, working with forms and capturing user input is an essential part of the development process. In React, you can easily handle forms and manage user input using state.
Handling Form Submission
To handle form submissions in React, you need to attach an event handler to the form's onSubmit
event. This event handler is responsible for performing any necessary actions when the form is submitted.
For example, let's create a simple form that collects the user's name and email address:
1const [name, setName] = useState('');
2const [email, setEmail] = useState('');
3
4const handleSubmit = (e) => {
5 e.preventDefault();
6 console.log('Form submitted');
7 console.log('Name:', name);
8 console.log('Email:', email);
9};
10
11return (
12 <form onSubmit={handleSubmit}>
13 <label htmlFor='name'>Name:</label>
14 <input type='text' id='name' value={name} onChange={(e) => setName(e.target.value)} />
15
16 <label htmlFor='email'>Email:</label>
17 <input type='email' id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
18
19 <button type='submit'>Submit</button>
20 </form>
21);
In this example, we start by declaring two state variables - name
and email
- using the useState
hook. The handleSubmit
function is called when the form is submitted. It prevents the default form submission behavior and logs the form data to the console.
The input fields are connected to their respective state variables using the value
and onChange
attributes. When the user types in the input fields, the state variables are updated accordingly.
Feel free to customize the form and add additional fields as needed. You can also perform validation and implement more complex form handling logic to suit your application's requirements.
xxxxxxxxxx
export default FormExample;
import React, { useState } from 'react';
const FormExample = () => {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form submitted');
console.log('Name:', name);
console.log('Email:', email);
};
return (
<div>
<h2>Form Example</h2>
<form onSubmit={handleSubmit}>
<label htmlFor='name'>Name:</label>
<input type='text' id='name' value={name} onChange={(e) => setName(e.target.value)} />
<label htmlFor='email'>Email:</label>
<input type='email' id='email' value={email} onChange={(e) => setEmail(e.target.value)} />
<button type='submit'>Submit</button>
</form>
</div>
);
};