React — Handling Forms in React
React handles forms using controlled components, where form data is handled by the component's state.
You use onChange
to update state and value
to control the input.
import React, { useState } from 'react';
function Form() {
const [name, setName] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitted name: ${name}`);
};
return (
<form onSubmit={handleSubmit}>
<input type=\"text\" value={name} onChange={(e) => setName(e.target.value)} />
<button type=\"submit\">Submit</button>
</form>
);
}