skip to Main Content

I need to submit the form with react hook form with zod validation. But in my condition, the submit button was outside of the form tag. So I used the id form method. ( please sudjust any other method as well. )

<form onSubmit={methods.handleSubmit(onSubmit)} id="sequenceForm">
   <label htmlFor="startDate">Start Date</label>
   <DatePickers name="startDate" id="startDate" />
</form>

    <button
    form="sequenceForm"
    onClick={() => {
    setDialogOpen(false);
     }}
    >
    Save
    </button>

>! not working
    <Button
    form="sequenceForm"
    onClick={() => {
    setDialogOpen(false);
     }}
     >
     Save
    </Button>

I need to use MUI button with form props as like as button field.

2

Answers


  1. Chosen as BEST ANSWER
    const formRef = useRef(null);
    formRef.current.requestSubmit();
    

    submit with requestSubmit works for me.


  2. you could have the button call your own form submit function. for example:

    const formRef = useRef(null);
    const handleClickSubmit = () => {
        if (formRef && formRef.current){
            setDialogOpen(false);
            formRef.current.submit();
        }
    }
    return (
        <form ref={formRef} onSubmit={methods.handleSubmit(onSubmit)}>{
            /* your form */}
        </form>
        <Button onClick={handleClickSubmit}>Save</Button>
    )
    

    i’m not 100% sure that is how you submit the form using a ref, but hopefully the idea itself is helpful.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search