Skip to content

Instantly share code, notes, and snippets.

@brookslybrand
Created October 24, 2023 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brookslybrand/fd0e173a41e0c484b639b6a78723be32 to your computer and use it in GitHub Desktop.
Save brookslybrand/fd0e173a41e0c484b639b6a78723be32 to your computer and use it in GitHub Desktop.
Progressively Enhanced Form with HTTP verbs
// Progressively enhanced form with HTTP verbs
const FormWithMethod = forwardRef<HTMLFormElement, FormProps>(
({ method, children, ...props }, ref) => {
const cleanMethod =
typeof method === "string" ? method.toUpperCase() : "POST";
return (
<Form
ref={ref}
// @ts-expect-error we'll get there
method={cleanMethod}
{...props}
>
<input type="hidden" name="_method" value={cleanMethod} />
{children}
</Form>
);
}
);
// Use in action functions
async function getRequestFormData(request: Request) {
const formData = await request.formData();
const method = formData.get("_method");
formData.delete("_method");
const entries = Object.fromEntries(formData.entries());
return { ...entries, method };
}
@brookslybrand
Copy link
Author

Not a recommendation that anyone do this, but if I wanted to use HTTP verbs with forms instead of just GET/POST, I think I would do it this way

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment