[shadcn/ui] AlertDialogでAlertDialogTriggerを使わずにダイアログを開く方法、AlertDialogActionを押した時に関数を呼び出す方法

Next.js

shadcn/uiのAlertDialogでAlertDialogTriggerを使わずにダイアログを開く方法、AlertDialogActionを押した時に関数を呼び出す方法について説明します。

広告

ソースコード

AlertDialogでAlertDialogTriggerを使わずにダイアログを開閉するには、useStateの変数を用意して、AlertDialogのopenプロパティとonOpenChangeプロパティに渡します。

AlertDialogActionを押した時に関数を呼び出すには、Buttonと同じようにonClickプロパティに実行する関数を渡します。

const [isDialogOpen, setIsDialogOpen] = useState<boolean>(false);

const myFunc = () => {
    console.log('myFunc');
}

// ...

<AlertDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
    {/* <AlertDialogTrigger asChild>
        <Button variant="outline">Show Dialog</Button>
    </AlertDialogTrigger> */}
    <AlertDialogContent>
        <AlertDialogHeader>
            <AlertDialogTitle>タイトル</AlertDialogTitle>
            <AlertDialogDescription>
                説明文。
            </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
            <AlertDialogCancel>キャンセル</AlertDialogCancel>
            <AlertDialogAction
                onClick={myFunc}
            >OK</AlertDialogAction>
        </AlertDialogFooter>
    </AlertDialogContent>
</AlertDialog>

広告