0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【React】shadcn/uiのDialogの開閉を独自の変数で管理したい

Posted at

概要

shadcn/uiのDialogに関して、Dialogのドキュメントでは開閉はDialogTriggerを使用した実装しか紹介されてません(2025年11月時点)。DialogTriggerだけだと、例えば該当のコンポーネントの外から開閉の制御をしたい場合は対応できません。
元々はradix-uiがベースなので独自の変数でも開閉を制御可能であり、その実装をメモ書きで残しておきます。

前提

  • @radix-ui/react-dialogのバージョンは1.1.15です。

対応方法

radix-ui側の実装サンプルClose after asynchronous form submission
にある通り、openとonOpenChangeに独自で定義した変数を設定することで実現できます。

実装サンプル

コンポーネントの外からDialogを制御するために、openとonOpenChangeに設定する項目をpropで受け取る実装です。

type Props = {
  isOpen: boolean;
  setIsOpen: (isOpen: boolean) => void;
};

export const SampleDialogComponent: FC<Props> = ({ isOpen, setIsOpen }) => {
  return (
    <Dialog open={isOpen} onOpenChange={setIsOpen}>
      <DialogContent>
        サンプル
      </DialogContent>
    </Dialog>
  );
};
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?