shadcn-ui / ui

Beautifully designed components that you can copy and paste into your apps. Accessible. Customizable. Open Source.
https://ui.shadcn.com
MIT License
67.11k stars 3.93k forks source link

[bug]: shadcn dialog with react hook forms and zod validation close button issue #3843

Open chaikovskiy99 opened 3 months ago

chaikovskiy99 commented 3 months ago

Describe the bug

I have a shadcn dialog, there is a form inside it that uses react-hook-forms and zod validation, the problem is that when I have mode: all selected like this, useForm({mode: 'all'}) , on clicking the close dialog button, I get the validation error messages displayed since I am using formState errors property to display validation errors. I have to click the close button twice to close the dialog. Is this expected behavior? image

Affected component/components

Dialog

How to reproduce

  1. Create a simple form with react-hooks-form useForm() hook, and zod validation schema.
  2. Add mode all in useForm({mode: 'all'})
  3. Put the form inside the dialog and try to close the dialog with the close button,
  4. On clicking the first. time, the dialog won't close, if there are any validation errors,
  5. On clicking the 2nd time, it will close

Codesandbox/StackBlitz link

No response

Logs

No response

System Info

MacOs 14.5 , Firefox, Brave

Before submitting

OmarAljoundi commented 3 months ago

I'm not sure, but I guess since every button has a type of "submit" by default. Setting the button type of the close button as "button" should fix your problem, in you dialog.tsx/jsx

Let me know if it works with you!

chaikovskiy99 commented 3 months ago

I'm not sure, but I guess since every button has a type of "submit" by default. Setting the button type of the close button as "button" should fix your problem, in you dialog.tsx/jsx

* Scroll to the **DialogContent**

* Inside it find the **DialogPrimitive.Close** component

* add the `type="button" ` to the **DialogPrimitive.Close** component like this:
   <DialogPrimitive.Close
       type="button"
       className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
        <X className="h-4 w-4" />
        <span className="sr-only">Close</span>
   </DialogPrimitive.Close>

Let me know if it works with you!

I tried that, however, it didn't work - same behavior. Nevertheless, for the time being I am going to use mode: 'onSubmit', that works well and I think it's enough for my current requirement. Thanks for your prompt reply.

2632755669 commented 2 months ago

I have the same problem,there is a form inside the dialog, input some words in the Input element,the words will selected when i click other place

2632755669 commented 2 months ago

image it will selected