React Forms
React Forms
In React, handling forms involves capturing user input, managing the state of form components, and responding to user interactions.
Here's a basic guide on how to work with forms in React:
Controlled Components:
React recommends using controlled components for forms. In a controlled component, form data is handled by the state of a React component. Here's a simple example:
import React, { useState } from 'react';
const MyForm = () => {
const [formData, setFormData] = useState({
username: '',
password: ''
});
const handleChange = (event) => {
const { name, value } = event.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (event) => {
event.preventDefault();
// Handle form submission using formData
console.log(formData);
};
return (
<form onSubmit={handleSubmit}>
<label>
Username:
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
</label>
<label>
Password:
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
</label>
<br />
<button type="submit">Submit</button>
</form>
);
};
export default MyForm;
In this example: