Form Handling in React
Working with forms and handling form input is a common task in web development, and React provides convenient ways to handle this.
In React, you can create a form component that maintains its own state separate from the global state. This makes it easier to manage form inputs and perform form validation.
Here's an example of a simple form component in React:
1function MyForm() {
2 const [name, setName] = React.useState('');
3 const [email, setEmail] = React.useState('');
4
5 const handleSubmit = () => {
6 // Handle form submission logic
7 };
8
9 return (
10 <form onSubmit={handleSubmit}>
11 <label>
12 Name:
13 <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
14 </label>
15 <label>
16 Email:
17 <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
18 </label>
19 <button type="submit">Submit</button>
20 </form>
21 );
22}
23
24ReactDOM.render(<MyForm />, document.getElementById('root'));
In this example, we define a form component MyForm
that uses the useState
hook to manage the state of the form inputs (name
and email
).
The handleSubmit
function is called when the form is submitted. You can implement the logic to handle form submission in this function.
The form component renders an HTML form
element with two input fields (name
and email
) and a submit button. The value
and onChange
attributes are used to bind the input fields to the state variables.
Try running the code snippet above and see how the form behaves. You can enter values in the input fields and click the submit button to see the form submission logic in action.
xxxxxxxxxx
function MyForm() {
const [name, setName] = React.useState('');
const [email, setEmail] = React.useState('');
const handleSubmit = () => {
// Handle form submission logic
};
return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" value={name} onChange={(e) => setName(e.target.value)} />
</label>
<label>
Email:
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</label>
<button type="submit">Submit</button>
</form>
);
}
ReactDOM.render(<MyForm />, document.getElementById('root'));