Skip to content

Kaundur/Modalyze

Repository files navigation

Modalyze

npm version license

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.

Features

  • 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

Live Demo

See Modalyze in action:

Open in StackBlitz

Installation

npm install modalyze
# or
yarn add modalyze
# or
pnpm add modalyze

Quick Start

1. 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.

Usage Guide

Creating and Closing Modals

How do I create a modal?

Call the createModal() function from the useModalyze() hook, const {createModal} = useModalyze(). The <Modalyze> component must also be included somewhere in your app

How do I close a modal?

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();

Working with Context

How do I access context within a modal?

Just use hooks normally, context is preserved. The modal accesses context from the nearest parent <Modalyze/> provider from where createModal() is called

How do I share state between the page and modal?

Put the state within a context, access it from both places

Why aren't my props updating in the modal?

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.

Advanced Scenarios

How do I control where new modals appear?

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.

How do I close a specific modal programmatically?

Save the ID: const id = createModal(...) then closeModal(id)

How do I prevent duplicate modals from opening?

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

How do I handle multiple context providers?

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>
);

How does context capture work?

  1. createModal() creates the modal element at the nearest <Modalyze> parent, capturing context at that level
  2. The modal is portaled up to the root <Modalyze> component
  3. The root renders all modals in a shared stack, enabling proper ordering while preserving each modal's captured context

Can I have multiple <Modalyze> roots?

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.

How can I prevent a modal from closing?

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.

API Reference

Modalyze Component <Modalyze>

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>

Modalyze Hook useModalyze()

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 ID
  • closeAllModals(): void - Closes all open modals
  • setModalCloseRequestHandler(modalId: string, handler: ModalCloseHandler | null): void - Sets a handler to intercept close requests. Return false to prevent closure. Pass null to remove the handler.
  • setFocusedModal(modalId?: string): void - Focuses the specified modal, or clears focus if no ID provided
  • bringModalToFront(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 modals
  • focusedModalId: string | null - ID of the currently focused modal
  • frontModalId: string | null - ID of the topmost modal in the stack

ModalyzeModal hook useModalyzeModal()

Functions

  • close() - Close this modal
  • setCloseRequestHandler(handler: ModalCloseHandler | null): void - Sets a handler to intercept close requests. Return false to prevent closure. Pass null to remove handler.
  • setSize(width: number, height: number): {width: number, height: number} | null - Set the size of the current modal, returns the updated size
  • setPosition(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 modal
  • isFocusedModal: boolean - Whether this modal is currently focused
  • isTopModal: boolean - Whether this modal is at the top of the stack

Types

Modal Configuration

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;
};

Close Request Handling

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;
});

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages