In React, forms and controlled components are essential for managing form data efficiently. A controlled component is a component that does not maintain its own state for input fields but instead receives its current value and change handler as props. This allows you to have a single source of truth for the form data, making it easier to manage.
Here’s a simple example of how to create a controlled component in a React functional component:
import React, { useState } from 'react'; const MyForm = () => { const [formData, setFormData] = useState({ name: '', email: '', }); const handleChange = (event) => { const { name, value } = event.target; setFormData((prevData) => ({ ...prevData, [name]: value, })); }; const handleSubmit = (event) => { event.preventDefault(); console.log('Form submitted:', formData); // Here you can handle form submission (e.g., sending data to an API) }; return ( <form onSubmit={handleSubmit}> <div> <label> Name: <input type="text" name="name" value={formData.name} onChange={handleChange} /> </label> </div> <div> <label> Email: <input type="email" name="email" value={formData.email} onChange={handleChange} /> </label> </div> <button type="submit">Submit</button> </form> ); }; export default MyForm;
State Management:
Handle Change:
Handle Submit:
Controlled Inputs:
Feel free to ask if you need more examples or specific implementations!
The above is the detailed content of Forms and Controlled Components. For more information, please follow other related articles on the PHP Chinese website!