- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Form Submission and Validation
Forms and Inputs
Form Submission and Validation
Put
onSubmiton the form, notonClickon the button. That one choice gets you Enter-to-submit and browser validation for free.
Submitting
A form submits when the button is clicked or Enter is pressed in a field. Handling it on the form catches both; handling the button's click catches only one, and keyboard users notice.
onSubmit and preventDefault
jsx
function Signup() {
const [email, setEmail] = React.useState("")
const [sent, setSent] = React.useState(null)
function handleSubmit(event) {
event.preventDefault() // stop the browser reloading the page
setSent(email)
setEmail("")
}
return (
<form onSubmit={handleSubmit}>
<input
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="you@example.com"
/>{" "}
<button type="submit">Sign up</button>
{sent && <p style={{ color: "#15803d" }}>Submitted: {sent}</p>}
<p style={{ color: "#64748b" }}>Press Enter in the field — it submits too.</p>
</form>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Signup />)