useModal hook provides access to modal state and modal actions from modal context, and it can be used in two different modes: global mode (without key) and scoped mode (with key).ts
import { useModal } from "@arkyn/components";
key (optional)stringkey is provided.ModalContextProps<T> | { modalIsOpen: boolean; modalData: T; openModal: (data?: T) => void; closeModal: () => void }key (global mode)modalIsOpen(key: string): boolean
Checks whether a specific modal is open.modalData(key: string): T
Reads the data associated with a specific modal key.openModal(key: string, data?: T): void
Opens the modal for the provided key and optionally stores data.closeModal(key: string): void
Closes the modal for the provided key.closeAll(): void
Closes every currently open modal.key (scoped mode)modalIsOpen: boolean
Boolean state for the current scoped modal.modalData: T
Data stored for the current scoped modal.openModal(data?: T): void
Opens only the scoped modal and optionally stores data.closeModal(): void
Closes only the scoped modal.closeAll is not returned because the hook is bound to a single key.key)tsx
import { ModalProvider, useModal } from "@arkyn/components";function ModalActions() {const {modalIsOpen,modalData,openModal,closeModal,closeAll} = useModal<{id: number}>();const userModalOpen = modalIsOpen("user");const userData = modalData("user");return (<div><p>Is user modal open? {String(userModalOpen)}</p><p>Current user id: {userData?.id ?? "none"}</p><button onClick={() => openModal("user", { id: 123 })}>Open user modal</button><button onClick={() => closeModal("user")}>Close user modal</button><button onClick={closeAll}>Close all modals</button></div>);}function App() {return (<ModalProvider><ModalActions /></ModalProvider>);}
key)key to the useModal hook. This simplifies the returned values and avoids repeating the modal key in every call.tsx
import {ModalProvider,useModal,ModalContainer,ModalHeader,} from "@arkyn/components";function UserModal() {const {modalIsOpen,modalData,closeModal} = useModal("user");return (<ModalContainer isVisible={modalIsOpen} makeInvisible={closeModal}><ModalHeader>Update user - {modalData?.id}</ModalHeader><button onClick={closeModal}>Close</button></ModalContainer>);}function ModalActions() {const { openModal } = useModal("user");return <Button onClick={openModal}>Open user modal</Button>;}function App() {return (<ModalProvider><ModalActions /><UserModal /></ModalProvider>);}
useModal outside provider scope throws an error.