ui
ui copied to clipboard
How can we close out the dialog from an action button?
So, in an example, where we use a form inside a dialog content so typically the form consists of input elements and a button of type submit because I am not using the dialog's builtin close primitive button, how can I pass or make a dialog close function and pass it on to the form action when form is successfully executed.
Example code:
<form onSubmit={(e) => {
// perform submit function here
closeDialog() // closes the dialog in the end
}} method="post">
<input type="email" name="test" id="test" />
<button type="submit"></button> // the form action button
</form>
Hi @milindgoel15, you can use useState to decide when the dialog should be opened. (I hope this is what you want achieve, otherwise let me know)
Check this example:
import { useState } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogTrigger,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
export function DialogFormDemo() {
const [open, setOpen] = useState(false);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger>Open</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Are you absolutely sure?</DialogTitle>
<DialogDescription>
<form
onSubmit={(e) => {
setOpen(false);
}}
>
<Input type="text" placeholder="Type 'yes' to confirm" />
<Button type="submit">Submit</Button>
</form>
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
);
}
That worked great, thanks.