I am trying to prevent closing the Sheet
component from shadcn/ui when validations on the data input by the user inside the sheet component fails. Currently, when button is clicked, even if there are validation errors handled by the Form
, the Sheet
closes and I have to manually reopen the component to fix the issue. The code is as follows
<Sheet>
<SheetTrigger asChild>...</SheetTrigger>
<SheetContent>
<div className="grid gap-4 py-4">
<Form { ...form }>
<form onSubmit={ form.handleSubmit(onSubmit) } className="w-full space-y-6">
...
<SheetFooter>
<SheetClose asChild>
<Button type="submit">Save changes</Button>
</SheetClose>
</SheetFooter>
</form>
</Form>
</div>
</SheetContent>
</Sheet >
I tried adding properties like aria-errormessage
, onError
and onErrorCapture
to the SheetClose
element, but that doesn't prevent closing the sheet.
aria-errormessage='Please correct all errors'
onError={ (event) => event.preventDefault }
onErrorCapture={ (event) => event.preventDefault }
You can acheive this in many ways. One of them is to:
<Sheet />
controlledconst [isOpen, setIsOpen] = useState(false);
return (
<Sheet
open={isOpen}
onOpenChange={(newValue) => {
if (newValue) setIsOpen(true); // when it's closed, allow opening it
// when it's opened
if (form.isValid) setIsOpen(newValue);
// otherwise, don't do anything
}}
>
...
</Sheet>
)