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:
const [formData, setFormData] = useState({
username: '',
password: ''
});
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({
...formData,
[name]: value
});
};
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
/>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
/>
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.