Forms in React
Forms are an important part of any web application, as they allow users to input and submit data. In React, we can handle forms and capture user input using various techniques.
One common approach is to use React's useState
hook to manage the state of form inputs. By setting up state variables for each input field, we can capture user input and update the state as the user types.
Let's take a look at an example:
1// Handling form data in React
2
3import React, { useState } from 'react';
4
5function Form() {
6 const [name, setName] = useState('');
7 const [email, setEmail] = useState('');
8
9 const handleNameChange = (event) => {
10 setName(event.target.value);
11 };
12
13 const handleEmailChange = (event) => {
14 setEmail(event.target.value);
15 };
16
17 const handleSubmit = (event) => {
18 event.preventDefault();
19 console.log('Form submitted');
20 console.log('Name:', name);
21 console.log('Email:', email);
22 // Perform form submission logic
23 };
24
25 return (
26 <form onSubmit={handleSubmit}>
27 <label>
28 Name:
29 <input type="text" value={name} onChange={handleNameChange} />
30 </label>
31 <br />
32 <label>
33 Email:
34 <input type="email" value={email} onChange={handleEmailChange} />
35 </label>
36 <br />
37 <button type="submit">Submit</button>
38 </form>
39 );
40}
41
42export default Form;
In the example above, we have a Form
component that renders a form with input fields for Name
and Email
. We initialize state variables using the useState
hook and provide initial values for the inputs.
We also define event handler functions, such as handleNameChange
and handleEmailChange
, which update the respective state variables as the user types.
The form submission is handled by the handleSubmit
function, which prevents the default form submission behavior and logs the form data to the console.
By using the useState
hook and event handlers, we can easily capture and handle user input in React forms.
xxxxxxxxxx
export default Form;
// Handling form data in React
import React, { useState } from 'react';
function Form() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const handleNameChange = (event) => {
setName(event.target.value);
};
const handleEmailChange = (event) => {
setEmail(event.target.value);
};
const handleSubmit = (event) => {
event.preventDefault();
console.log('Form submitted');
console.log('Name:', name);
console.log('Email:', email);
// Perform form submission logic
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={handleNameChange} />