ui icon indicating copy to clipboard operation
ui copied to clipboard

How can we close out the dialog from an action button?

Open milindgoel15 opened this issue 1 year ago • 1 comments

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>

milindgoel15 avatar Feb 07 '24 09:02 milindgoel15

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>
  );
}

dan5py avatar Feb 07 '24 17:02 dan5py

That worked great, thanks.

milindgoel15 avatar Feb 09 '24 05:02 milindgoel15