DEV Community

Cojiroooo
Cojiroooo

Posted on

How does Form submit as a default event?

Use a trigger provided react-hook-form and call this in custom submit method.
This approach is using basic JavaScript.

const formSchema = z.object({
  name: z.string(),
});
const Form = () => {
  const { register, trigger } = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
  });

  const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    const isValid = await trigger();
    if (!isValid) {
      e.preventDefault();
      return;
    }
    // if you want to add something to the form, you can write it here.
  };

  return (
    <form onSubmit={onSubmit}>
      <input {...register('name')} />
      <button type="submit">Submit</button>
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

I develop the react application on MPA, so I needed to send a form by not ajax.

Top comments (0)