Why does the alert modal I created in ShadCn automatically close as soon as I click on it?

There is an action that I created which displays a menu, and I implemented a function where if the user selects delete, a warning alert is shown before proceeding. However, the issue I am facing now is that when I click on the menu, the modal opens but immediately closes. It seems like it closes because the menu closes right after it is clicked.

import Image from 'next/image';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Trash2 } from 'lucide-react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';

export default function Home() {
  return (
    <div>
      <DropdownMenu>
        <DropdownMenuTrigger>Open</DropdownMenuTrigger>
        <DropdownMenuContent>
          <DropdownMenuLabel>My Account</DropdownMenuLabel>
          <DropdownMenuSeparator />
          <DropdownMenuItem>
            <Trash2 className="mr-2 h-4 w-4" />
            <AlertDialog>
              <AlertDialogTrigger>Open</AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
                  <AlertDialogDescription>
                    This action cannot be undone. This will permanently delete
                    your account and remove your data from our servers.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                  <AlertDialogAction>Continue</AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </DropdownMenuItem>
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}

I have created a demonstration here

Answer №1

The issue with your current setup is that the dialog content is defined within the menu item. When you click on the menu item, the dialog renders for a brief moment, but then the menu is removed from the DOM along with the dialog content, causing them to disappear.

A quick solution to resolve this is to enclose the menu item in an alert dialog and relocate the dialog content outside of the menu item. Here's how you can do it:

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { Trash2 } from 'lucide-react';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';

export default function Home() {
  return (
    <div>
      <AlertDialog>
        <DropdownMenu>
          <DropdownMenuTrigger>Open</DropdownMenuTrigger>
          <DropdownMenuContent>
            <DropdownMenuLabel>My Account</DropdownMenuLabel>
            <DropdownMenuSeparator />
            <DropdownMenuItem>
              <Trash2 className="mr-2 h-4 w-4" />
              <AlertDialogTrigger>Open</AlertDialogTrigger>
            </DropdownMenuItem>
          </DropdownMenuContent>
        </DropdownMenu>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete your
              account and remove your data from our servers.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction>Continue</AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

react Concealing the Card upon clicking a different location

Utilizing a combination of React and TypeScript, this component allows for the card to be toggled between shown and hidden states upon clicking on the specified div tag. However, there is a need to ensure that the card is hidden even if another area outs ...

Using the fetch/await functions, objects are able to be created inside a loop

In my NEXTJS project, I am attempting to create an object that traverses all domains and their pages to build a structure containing the site name and page URL. This is required for dynamic paging within the getStaticPaths function. Despite what I believe ...

Error with Background component in Next.js-TypeScript when trying to change color on mouseover because Window is not defined

Within my Background component, there is a function that includes an SVG which changes color upon mouseover. While this functionality works fine, I encountered an error when hosting the project using Vercel - "ReferenceError: window is not defined." This i ...

Are multiple click events needed for identical buttons?

In my component, there is an HTML structure like this: <div id="catalogo" class="container"> <div class="row"> <div *ngFor="let artista of artistas" class="col-sm" style="mar ...

The mistake occurred when 'mongoose/dist/browser.umd.js' was imported into './src/models/userModel.js'

Encountered a compilation error. Issue found in './src/models/userModel.js': The Edge Runtime does not allow Dynamic Code Evaluation (e.g., 'eval', 'new Function', 'WebAssembly.compile'). For more information, visit ...

Server-side props become inaccessible on the client side due to middleware usage

I'm attempting to implement a redirect on each page based on a specific condition using Next.js middleware. Strange enough, when the matcher in middleware.ts matches a page, all props retrieved from getServerSideProps for that page end up being undef ...

"Challenges encountered when trying to populate a select field with information retrieved from

I am currently working on a project using NextJS version 13.4.7 with react, and I am facing an issue while trying to update data in a select field with information fetched from an API call. Upon initial page load, I have set a default option field and valu ...

Creating individual product pages from an array of objects: A step-by-step guide

Is there a way in Next.js to create individual pages for each object in an array with unique URLs? Here is the input array: Input Array const products = [ { url: "item-1", id: 1, name: "Item 1", description: "lor ...

Is it possible to pass a specific region to a language in nextjs i18n?

Suppose I am in favor of the languages ['en', 'de']. In this case, I would like to redirect requests with a header such as Accept-Language: de-DE to de since it is the most closely related to what I support. // Below is my i18n configur ...

What is the best way to change an existing boolean value in Prisma using MongoDB?

Exploring prisma with mongoDb for the first time and faced a challenge. I need to update a boolean value in a collection but struggling to find the right query to switch it between true and false... :( const updateUser = await prisma.user.update({ where: ...

Implementing the "$store" property within Vue components

Click here for a guide on how to type the $store property. Unfortunately, I've been encountering issues with it. In my Vue 2 project created using vue-cliI, I included a vuex.d.ts file in ./src directory but the $store property in my components still ...

Tips for incorporating transition animations into route changes in next.js

On the homepage, there are 2 links that I want to have distinct transition animations for. For example, if I click the link on the left, the animation should start from the left and move towards the right when changing routes. ...

Obtaining information upon the loading of a Modal in a Next.js application

I am currently developing a feature for my application that allows users to add a new project to a timesheet system. To achieve this, I have created a Modal with a form inside. The form includes a Select field that should display all existing user names f ...

Accessing the observable's value by subscribing to it

There is a defined observable called imageOptions$ in my code: imageOptions$: Observable<BoundImagesToProject[]> = this.imagesService .getBoundImages({ projectId: this.projectId }) .pipe(map((images) => (images.data))); and it is used in the temp ...

Leverage HTML within JSON for a multilingual website using i18next with Next.js

I am working on a multi-language website using Next.js. To handle the translations, I am using the package i18next. In my JSX code, I define variables like this: {t("satisfied:title")} This means {t("JSONfileName:JSONvariable")} However, when I try to i ...

Enhancing Styled Components in Material-UI with custom props and themes using Typescript

I am exploring the use of the Material UI styled components API to incorporate both a custom theme and some props into a specific custom element. Although I have managed to get either a custom theme or props working individually, I am struggling to make t ...

Angular 2: The linting error shows up as "Anticipated operands need to be of the same type or any"

So, I have this shared service file where a variable is defined like so: export class SharedService { activeModal: String; } Then, in my component file, I import the service and define it as follows: constructor(public sharedService: SharedService) ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Determining the presence of generic K within generic M in Typescript Generics and Redux

Hello there I am currently working on minimizing repetitive code in my react application by utilizing Redux state. After choosing the Redux structure to use (refer to Context), I now aim to make it more concise. To achieve this, I have developed a generic ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...