React · Lesson 28 of 120
Submitting Forms
OnSubmit.
Forms submit when the user presses enter or clicks the submit button. In React, handle the form's on submit event, and stop the browser reloading the page.
- Enter or click
- onSubmit
- No page reload
A newsletter form
Handle submit first calls prevent default, so the page doesn't reload. Then it saves the email, and clears the input. We type an email, and press enter. Run it.
App.jsxjsx
import { useState } from "react";
export default function App() {
const [email, setEmail] = useState("");
const [joined, setJoined] = useState([]);
function handleSubmit(e) {
e.preventDefault();
setJoined([...joined, email]);
setEmail("");
}
return (
<form onSubmit={handleSubmit}>
<input id="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" />
<button>Join</button>
<p>Joined: {joined.join(", ") || "nobody yet"}</p>
</form>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"type": "#email", "text": "priya@example.com"}, {"key": "Enter"}]Summary
Handle on submit on the form, and call prevent default first. Next, validation.
Key takeaways- onSubmit
- e.preventDefault()
- Then save
Next up: Validation — showing errors