shadcn/ui page reloads on form submit

I have this code to submit on enter on the form but the page reloads on the submit:
<Form {...textMessageForm}>
<form
onSubmit={textMessageForm.handleSubmit(
onTextMessageFormSubmit,
)}
className="w-10/12"
ref={formRef}
>
<FormField
control={textMessageForm.control}
name="message"
render={({ field }) => (
<FormControl>
<Input
className="ml-4 w-full bg-secondary p-2"
placeholder="Message ..."
onKeyUp={(event) => {
if (event.code === "Enter") {
event.preventDefault();
formRef.current?.submit();
}
}}
{...field}
/>
</FormControl>
)}
/>
</form>
</Form>
<Form {...textMessageForm}>
<form
onSubmit={textMessageForm.handleSubmit(
onTextMessageFormSubmit,
)}
className="w-10/12"
ref={formRef}
>
<FormField
control={textMessageForm.control}
name="message"
render={({ field }) => (
<FormControl>
<Input
className="ml-4 w-full bg-secondary p-2"
placeholder="Message ..."
onKeyUp={(event) => {
if (event.code === "Enter") {
event.preventDefault();
formRef.current?.submit();
}
}}
{...field}
/>
</FormControl>
)}
/>
</form>
</Form>
4 Replies
kewinzaq1
kewinzaq1•7mo ago
Hi I'll help you but I have a few questions. Why are you using doubled form? I guess that the custom Form component already uses native form under the hood, so you probably don't need the second one. Secondly you should prevent default form behavior not input event. @FleetAdmiralJakob 🗕 🗗 🗙
FleetAdmiralJakob 🗕 🗗 🗙
React Hook Form
Building forms with React Hook Form and Zod.
pappu
pappu•7mo ago
If you preventDefault and then void the function call everything works great. I have it as this:
<Form {...form}>
<form
onSubmit={(e) => {
e.preventDefault();
void form.handleSubmit(onSubmit)();
}}

...

const onSubmit = (submission: z.infer<typeof formSchema>) => {
<Form {...form}>
<form
onSubmit={(e) => {
e.preventDefault();
void form.handleSubmit(onSubmit)();
}}

...

const onSubmit = (submission: z.infer<typeof formSchema>) => {
janglad
janglad•7mo ago
assuming this is react hook form the default should already be prevented no? altho maybe the ref is somehow messing with that?
Want results from more Discord servers?
Add your server