dynamic-modal
Version:
The dynamic-modal is a solution of creation different modals into project using a json configuration file
40 lines (39 loc) • 1.46 kB
JavaScript
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { useEffect, useReducer } from 'react';
import { createPortal } from 'react-dom';
const initialState = {
mounted: false,
node: null,
};
const portalReducer = (state, action) => {
if (action.type === 'OPEN') {
return {
mounted: !!action.node,
node: action.node,
};
}
if (!state.mounted && !state.node)
return state;
return initialState;
};
export const Portal = (props) => {
const [{ mounted, node }, dispatch] = useReducer(portalReducer, initialState);
useEffect(() => {
if (props.portalOpen) {
const portalNode = document.querySelector(props.portalTag ?? '#portal');
dispatch({ type: 'OPEN', node: portalNode });
return;
}
if (mounted && props.closeTime > 0) {
const timeoutId = setTimeout(() => {
dispatch({ type: 'CLOSE' });
}, props.closeTime);
return () => clearTimeout(timeoutId);
}
dispatch({ type: 'CLOSE' });
}, [mounted, props.closeTime, props.portalOpen, props.portalTag]);
if (!mounted || !node)
return null;
return createPortal(_jsx("div", { className: `transition-all delay-100 fixed top-0 left-0 w-full h-full grid place-items-center bg-black bg-opacity-40 z-20 ${props.useBlur && 'backdrop-blur-sm'}`, children: props.children }), node);
};