Context-aware modals for React
A React library for creating draggable, resizable, stackable modals that preserve React context. Create modals programmatically without losing access to your context providers.
- Context Preservation - Modals maintain access to React context
- Programmatic API - Create modals by calling
createModal() - Multiple Modals - Open and manage many modals at once
- Draggable & Resizable - Move and resize modals freely
- Cascading Layout - Multiple modals stack with natural offsets by default
- Smart Deduplication - Stable IDs prevent duplicate modals opening
- Zero Config - Drop in and use immediately
See Modalyze in action:
npm install modalyze
# or
yarn add modalyze
# or
pnpm add modalyze1. Add the <Modalyze> provider to your app
Place it below any context providers you want modals to access:
import { Modalyze } from 'modalyze';
function App() {
return (
<OtherProvider>
<Modalyze>
<BasicExample /> {/* Modals created here access OtherProvider */}
</Modalyze>
</OtherProvider>
);
}2. Create modals from any component
Use the useModalyze() hook to create modals:
import { useModalyze } from 'modalyze';
const BasicModal = () => {
return <div>Basic Modal</div>;
};
const BasicExample = () => {
const { createModal } = useModalyze();
return <button onClick={() => createModal(BasicModal)}>Open Modal</button>;
};That's it! Modals will have access to any context providers above the <Modalyze> component.
Call the createModal() function from the useModalyze() hook, const {createModal} = useModalyze(). The <Modalyze>
component must also be included somewhere in your app
Modals can be closed via ESC key, clicking outside, or both. Default is ESC only.
createModal(BasicModal, { closeOnEscape: true, closeOnOutsideClick: false });From within a modal
const { close } = useModalyzeModal();From outside a modal with the modal ID
const { closeModal } = useModalyze();
closeModal(modalId);Or close all modals
const { closeAllModals } = useModalyze();
closeAllModals();Just use hooks normally, context is preserved. The modal accesses context from the nearest parent <Modalyze/> provider
from where createModal() is called
Put the state within a context, access it from both places
Props passed via createModal() are captured at creation time and won't update. For live data that changes over time,
use React context instead. Context values will update reactively in your modal.
Pass position to createModal. By default, modals use a cascading layout that offsets each
new modal slightly from the last. Use "center" to always open at the center of the screen,
or { x, y } for an exact pixel position.
Save the ID: const id = createModal(...) then closeModal(id)
Pass a stable id to createModal. If a modal with that ID is already open, Modalyze will
focus it instead of creating a second one. The returned ID will match the string you passed,
so you can still close it later:
createModal(SettingsModal, { id: 'settings' });
closeModal('settings');Use toggleWhen to control what happens when the ID already exists:
- omitted (default) - focus the existing modal
'whenTop'- close it if it is the topmost modal, otherwise focus it'always'- always close it instead of focusing
Place a <Modalyze> within each provider level, context is preserved at the nearest parent <Modalyze> from which
createModal is called
return (
<div>
<OuterProvider>
<Modalyze>
<MainContainer />
<InnerProvider>
<Modalyze>
<InnerContainer />
</Modalyze>
</InnerProvider>
<InnerProvider>
<Modalyze>
<InnerContainer />
</Modalyze>
</InnerProvider>
</Modalyze>
</OuterProvider>
</div>
);createModal()creates the modal element at the nearest<Modalyze>parent, capturing context at that level- The modal is portaled up to the root
<Modalyze>component - The root renders all modals in a shared stack, enabling proper ordering while preserving each modal's captured context
Yes, but not recommended. Multiple root <Modalyze> components create separate modal stacks that can't be ordered
relative to each other, one stack will always render above the other.
Recommended: Use a single root <Modalyze> component, with nested <Modalyze> providers only for capturing
different context levels.
Use the closeOnEscape and closeOnOutsideClick options to prevent dismissing.
If you need to intercept the close request use the setCloseRequestHandler or setModalCloseRequestHandler depending
on if you're setting it from inside or outside the modal.
The main component. Must be included once to create modals, can be repeated to capture different context levels, but
should only be one root <Modalyze>
Functions
createModal<P>(component: ModalComponent<P>, options?: ModalCreationOptions<P>): string- Creates a modal imperatively while preserving React context. Returns the modal ID.closeModal(modalId: string): void- Closes a specific modal by IDcloseAllModals(): void- Closes all open modalssetModalCloseRequestHandler(modalId: string, handler: ModalCloseHandler | null): void- Sets a handler to intercept close requests. Returnfalseto prevent closure. Passnullto remove the handler.setFocusedModal(modalId?: string): void- Focuses the specified modal, or clears focus if no ID providedbringModalToFront(modalId: string): void- Brings the specified modal to the top of the stack
Observable State
modalIds: string[]- Array of all modal IDs in stack order (bottom to top)modalCount: number- Total number of open modalsfocusedModalId: string | null- ID of the currently focused modalfrontModalId: string | null- ID of the topmost modal in the stack
Functions
close()- Close this modalsetCloseRequestHandler(handler: ModalCloseHandler | null): void- Sets a handler to intercept close requests. Returnfalseto prevent closure. Passnullto remove handler.setSize(width: number, height: number): {width: number, height: number} | null- Set the size of the current modal, returns the updated sizesetPosition(x: number, y: number): {x: number, y: number} | null- Set the position of the current modal, returns the updated position
Observable State
modalId: string- ID for this modalisFocusedModal: boolean- Whether this modal is currently focusedisTopModal: boolean- Whether this modal is at the top of the stack
ModalBehaviorConfig
export type ModalBehaviorConfig = {
closeOnEscape?: boolean;
closeOnOutsideClick?: boolean;
minSize?: { width: number; height: number };
/** Position defaults to cascading, but can be fixed to the center or set to a px value */
position?: { x: number; y: number } | 'center';
} & (
| { id?: undefined; toggleWhen?: never }
| {
/** Stable ID for this modal. If a modal with this ID is already open, it will be focused instead of creating a new one. */
id: string;
/**
* Controls what happens when `createModal` is called with an `id` that already exists.
*
* - `'always'` - always close the existing modal instead of focusing it.
* - `'whenTop'` - close only if this modal is last in the render stack.
* - omitted - default: focus the existing modal.
*
* Has no effect when `id` is not supplied.
*/
toggleWhen?: 'always' | 'whenTop';
}
);ModalConfig
export type ModalConfig = ModalBehaviorConfig & {
title?: string;
size?: { width: number; height: number };
};ModalCreationOptions<P>
export type ModalCreationOptions<P = Record<string, unknown>> = ModalConfig & {
props?: P;
};ModalyzeCloseRequestEvent
export interface ModalyzeCloseRequestEvent {
reason: 'escape' | 'outside' | 'manual';
nativeEvent?: MouseEvent | TouchEvent | KeyboardEvent;
modalId: string;
source: 'internal' | 'external';
}ModalCloseHandler
export type ModalCloseHandler = (event: ModalyzeCloseRequestEvent) => boolean;Usage:
// From outside modal
const { setModalCloseRequestHandler } = useModalyze();
setModalCloseRequestHandler(modalId, (event) => {
if (hasUnsavedChanges) {
return confirm('Discard changes?');
}
return true;
});
// From inside modal
const { setCloseRequestHandler } = useModalyzeModal();
setCloseRequestHandler((event) => {
if (hasUnsavedChanges) {
return confirm('Discard changes?');
}
return true;
});