Skip to content

Commit

Permalink
update form submission pattern and documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Jacob Shandling committed Jan 23, 2025
1 parent 53e3014 commit 8ceca36
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 17 deletions.
25 changes: 15 additions & 10 deletions frontend/components/forms/ConfirmInviteForm/ConfirmInviteForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,17 +86,22 @@ const ConfirmInviteForm = ({
setFormErrors(errsToSet);
};

const onSubmit = useCallback(() => {
const errs = validate(formData);
if (Object.keys(errs).length > 0) {
setFormErrors(errs);
return;
}
handleSubmit(formData);
}, [formData, handleSubmit]);
const onSubmit = useCallback(
(evt: React.FormEvent<HTMLFormElement>) => {
evt.preventDefault();

const errs = validate(formData);
if (Object.keys(errs).length > 0) {
setFormErrors(errs);
return;
}
handleSubmit(formData);
},
[formData, handleSubmit]
);

return (
<form className={baseClass} autoComplete="off">
<form onSubmit={onSubmit} className={baseClass} autoComplete="off">
{ancestorError && <div className="form__base-error">{ancestorError}</div>}
<InputField
label="Full name"
Expand Down Expand Up @@ -130,7 +135,7 @@ const ConfirmInviteForm = ({
parseTarget
/>
<Button
onClick={onSubmit}
type="submit"
disabled={Object.keys(formErrors).length > 0}
className="confirm-invite-button"
variant="brand"
Expand Down
17 changes: 10 additions & 7 deletions frontend/docs/patterns.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,13 +202,16 @@ export default PackComposerPage;

## Forms

### Form buttons

When building a React-controlled form, use the `Button` component for its submit button, and do not
include a `type`, allowing it to default to `type="button"`, which is what we want. Using
`type="submit"` leads to confusing behavior wherein the native HTML submit functionality
interferes with our custom submit logic, causing the request to be canceled in a messy and hard to
recognize way. Alternatively, if using `type="submit"`, ensure the submit handler calls `evt.preventDefault`
### Form submission

When building a React-controlled form:
- Use the native HTML `form` element to wrap the form.
- Use a `Button` component with `type="submit"` for its submit button.
- Write a submit handler, e.g. `handleSubmit`, that accepts an `evt:
React.FormEvent<HTMLFormElement>` argument and, critically, calls `evt.preventDefault()` in its
body. This prevents the HTML `form`'s default submit behavior from interfering with our custom
handler's logic.
- Assign that handler to the `form`'s `onSubmit` property (*not* the submit button's `onClick`)

### Data validation

Expand Down

0 comments on commit 8ceca36

Please sign in to comment.