Form submission is the browser process of collecting values from an HTML form and sending them to the form’s target URL. A button inside a form submits it by default, which can reload the current page even when no target URL or inputs are specified. section 8.4.1
Handle submission in React by:
- Attach the handler to the form’s onSubmit event rather than only to the button’s onClick event. section 8.4.2
- Call evt.preventDefault() to stop the browser’s native submission and page reload. section 8.4.2
- Read controlled-input values from component state, then send them to a service or storage location. section 9.2.4
- Use the form submit event to support both clicking Submit and pressing Enter while an input has focus. section 9.2.4
React form handler
const onSubmit = (evt) => { evt.preventDefault(); handleAdd(data); }; return <form onSubmit={onSubmit}>...</form>; A to-do form stores title, category, and date in state, passes the collected object to its parent, and prevents the browser reload. section 9.2.4
Listing 8.8 Admin form (potentially fixed?)
import { useState } from "react";
function Admin() {
const [password, setPassword] = useState("");
const [isAdmin, setAdmin] = useState(false);
const onSubmit = (evt) => { #1
evt.preventDefault(); #2
if (password === "platypus") {
setAdmin(true);
}
};
return isAdmin ? (
<h1>Bacon is delicious!</h1>
) : (
<form onSubmit={onSubmit}> #3
<input
type="password"
onChange={(evt) => setPassword(evt.target.value)}
/>
<button>Login</button>
</form>
);
}
function App() {
return <Admin />;
}
export default App;
Browse a complete React admin form showing onSubmit, preventDefault, password state, and conditional rendering. section 8.4.2
