modal-manage.tsx
Overview
The modal-manage.tsx file provides a React-based mechanism for rendering modal dialogs dynamically via React portals. It includes two main parts:
PortalModalReact component – a controlled modal component that renders its content into a specified DOM container using React portals, handling visibility and lifecycle.createPortalModalfactory function – programmatically creates and manages modals outside the standard React component tree. It supports showing, hiding, updating, and destroying modals imperatively.
This file is designed to facilitate flexible, dynamic modal dialogs that can be created and managed at runtime, enabling modals to be rendered outside the main React app hierarchy while maintaining React state and lifecycle management.
Detailed Explanation
1. PortalModal Component
A React functional component that renders a modal dialog into a DOM node via React portals.
Signature
const PortalModal: React.FC<PortalModalProps>
Props (PortalModalProps)
Extends ModalProps with some adjustments:
visible: boolean
Controls whether the modal is shown or hidden.onVisibleChange: (visible: boolean) => void
Callback fired when modal visibility changes (e.g., when closed).container?: HTMLElement
Optional DOM element where the modal portal will render into. Defaults todocument.body.children: ReactNode
The content to render inside the modal.[key: string]: any
Additional props spread onto the underlyingModalcomponent.
Behavior
Uses
useEffectto set amountedstate to ensure modal renders only after mounting.If not mounted or not visible, returns
null(renders nothing).Uses React's
createPortalto render theModalcomponent into the specified container.Passes
visibleasopenprop and forwardsonVisibleChangeand other props to the underlyingModal.
Usage Example
<PortalModal
visible={isModalVisible}
onVisibleChange={(visible) => setIsModalVisible(visible)}
container={document.getElementById('modal-root')}
>
<div>Modal Content Here</div>
</PortalModal>
2. createPortalModal Factory Function
Imperative API to dynamically create and control a modal instance outside React's normal render tree.
Signature
function createPortalModal(): {
show: (props: PortalModalProps) => void;
hide: () => void;
update: (props?: Partial<PortalModalProps>) => void;
destroy: () => void;
}
Internal Implementation Details
Creates a detached
<div>element appended todocument.bodyto serve as the portal container.Creates a React root (
createRoot) for rendering the modal into that container.Maintains internal state variables:
currentProps: stores the current modal props.isVisible: tracks whether modal is currently shown.root: the React root for rendering.
Defines helper functions:
render(): updates the React root render with the current modal state.show(props): sets props, marks modal visible, and triggers render.hide(): marks modal hidden and triggers render.update(props): merges new props with current, triggers render.destroy(): unmounts modal, removes container from DOM, resets state.
Modal Visibility Handling
The
onVisibleChangeprop passed toPortalModalupdates the internalisVisiblestate.When modal visibility changes to false,
render()is called to unmount modal content.The external
onVisibleChangecallback is also invoked, enabling external consumers to respond to modal close events.
Usage Example
const modal = createPortalModal();
modal.show({
children: <div>Dynamic modal content</div>,
onVisibleChange: (visible) => {
console.log('Modal visibility changed:', visible);
}
});
// Later update modal content or props
modal.update({ children: <div>Updated content</div> });
// Hide modal
modal.hide();
// Destroy modal instance and cleanup DOM
modal.destroy();
Important Implementation Details and Algorithms
React Portals: The core technique used to render modal content outside the main React DOM hierarchy into a separate DOM node.
React 18 Root API (
createRoot): Used for rendering and re-rendering the modal imperatively.Imperative Modal Control: Unlike typical declarative React modals, this file allows creating and controlling modals programmatically, useful for modals triggered globally or outside component trees.
Lifecycle Management: Ensures proper mounting/unmounting and DOM cleanup to prevent memory leaks.
State Synchronization: Internal
isVisibleandcurrentPropstrack modal state to keep React root rendering in sync.
Interaction with Other Parts of the System
Imports the reusable
Modalcomponent from'./modal', which presumably implements the base modal UI and behavior.Relies on React and ReactDOM APIs (
createPortal,createRoot) for rendering.The exported
createPortalModalfunction is intended to be used by other parts of the application that need dynamic modal dialogs without embedding them directly in JSX.Can be integrated with global UI managers, context providers, or event handlers that require modal dialogs dynamically.
Visual Diagram
componentDiagram
component PortalModal {
+visible: boolean
+onVisibleChange(visible: boolean)
+container?: HTMLElement
+children: ReactNode
}
component createPortalModal {
+show(props: PortalModalProps)
+hide()
+update(props?: Partial<PortalModalProps>)
+destroy()
}
PortalModal <.. createPortalModal : uses
createPortalModal --> Modal : renders via PortalModal
Summary
The modal-manage.tsx file provides a robust, imperative API for creating and managing React modals dynamically via portals. It abstracts modal lifecycle and rendering into a reusable hook-like factory function, enabling modals to be controlled outside of React component trees while preserving React's declarative rendering model underneath. This design pattern is well-suited for global modal managers, notification systems, or any scenario requiring runtime modal injection with full React support.