Skip to content

Commit 4051fe9

Browse files
authored
feat(Dialog): add useDialogContainer hook (#611)
1 parent d7a7759 commit 4051fe9

4 files changed

Lines changed: 46 additions & 0 deletions

File tree

.changeset/stale-jobs-pump.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@cube-dev/ui-kit': minor
3+
---
4+
5+
Add useDialogContainer hook to manage dialogs.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import React, { useState, useMemo } from 'react';
2+
3+
import { useEvent } from '../../../_internal/index';
4+
5+
import { DialogContainer } from './DialogContainer';
6+
7+
/**
8+
* Generic hook to manage a dialog component.
9+
*
10+
* @param Component - A React component that represents the dialog content. It must accept props of type P.
11+
* @returns An object with `open` function to open the dialog with provided props and `rendered` JSX element to include in your component tree.
12+
*/
13+
export function useDialogContainer<P>(Component: React.ComponentType<P>) {
14+
const [isOpen, setIsOpen] = useState(false);
15+
const [componentProps, setComponentProps] = useState<P | null>(null);
16+
17+
// 'open' accepts props required by the Component and opens the dialog
18+
const open = useEvent((props: P) => {
19+
setComponentProps(props);
20+
setIsOpen(true);
21+
});
22+
23+
const close = useEvent(() => {
24+
setIsOpen(false);
25+
});
26+
27+
// Render the dialog only when componentProps is set
28+
const rendered = useMemo(() => {
29+
if (!componentProps) return null;
30+
31+
return (
32+
<DialogContainer isOpen={isOpen} onDismiss={close}>
33+
<Component {...componentProps} />
34+
</DialogContainer>
35+
);
36+
}, [componentProps, isOpen]);
37+
38+
return { open, close, rendered };
39+
}

src/components/overlays/Dialog/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ export * from './DialogContainer';
22
export * from './DialogForm';
33
export * from './DialogTrigger';
44
export * from './Dialog';
5+
export * from './dialog-container';

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ export {
8888
DialogTrigger,
8989
DialogContainer,
9090
DialogForm,
91+
useDialogContainer,
9192
} from './components/overlays/Dialog';
9293
export type {
9394
CubeDialogTriggerProps,

0 commit comments

Comments
 (0)