How to handle form inputs in React?

In React, form inputs are handled using controlled components. Controlled components are inputs whose value is controlled by the component’s state. Here’s how you can handle form inputs in React:

  1. Create a state object that will hold the values of the form inputs.
const [formData, setFormData] = useState({ username: '', password: '' });
  1. Create a handleChange function that updates the state object whenever a form input value changes.
const handleChange = (e) => { const { name, value } = e.target; setFormData({ ...formData, [name]: value }); };
  1. Add the value and onChange event handler to each form input that will be controlled.
<input type="text" name="username" value={formData.username} onChange={handleChange} /> <input type="password" name="password" value={formData.password} onChange={handleChange} />
  1. Handle form submission by using the state object that holds the form input values.
const handleSubmit = (e) => { e.preventDefault(); // Do something with the form data }; <form onSubmit={handleSubmit}> <input type="text" name="username" value={formData.username} onChange={handleChange} /> <input type="password" name="password" value={formData.password} onChange={handleChange} /> <button type="submit">Submit</button> </form>

By following these steps, you can easily handle form inputs in React using controlled components.