Created
October 24, 2023 22:24
-
-
Save brookslybrand/fd0e173a41e0c484b639b6a78723be32 to your computer and use it in GitHub Desktop.
Progressively Enhanced Form with HTTP verbs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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> | |
); | |
} | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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