I created this modal component:
interface ModalProps extends PropsWithChildren {
/***/
onClose: () => void;
}
const Modal: FC<ModalProps> = ({
/***/
onClose,
children
}) => {
const [isVisible, setIsVisible] = useState<boolean>(false);
useEffect(() => {
setIsVisible(true);
}, []);
function handleTransitionEnd() {
if (!isVisible) {
onClose();
}
}
return (
<div
className={clsx(
'fixed left-0 right-0 bottom-0 top-0 w-full z-[9999] bg-black/40 transition-opacity duration-300',
isVisible ? 'opacity-100' : 'opacity-0'
)}
onClick={() => setIsVisible(false)}
onTransitionEnd={handleTransitionEnd}
>
<div
className={clsx(
'bg-white absolute left-1/2 -translate-x-1/2 transition-transform duration-300 rounded-2xl overflow-auto',
isVisible ? 'bottom-4 translate-y-0' : 'bottom-0 translate-y-full'
)}
onClick={(event: React.MouseEvent<HTMLDivElement, MouseEvent>) =>
event.stopPropagation()
}
>
</div>
{children}
</div>
);
};
export default Modal;
And this is its parent component:
const Parent: FC = () => {
const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
return (
<div>
<button onClick={() => setIsModalVisible(true)}>Open Modal</button>
{isModalVisible && (
<Modal onClose={() => setIsModalVisible(false)}>
<div className="bg-white flex justify-center items-center">
<button onClick={() => setIsModalVisible(false)}>
Close Modal
</button>
</div>
</Modal>
)}
</div>
);
};
export default Parent;
I added some transition to modal when I open it the transition applies. when I click on X button modal or its backdrop it hides and also the transition applies. but when I click on Close Modal
button that I passed to it as child, in other word when I manage modal's display from parent's state the transition does not work. how can I change modal component to fix it?
PS: I also tried to pass the isVisible to modal and then I used an useEffect on it but did not work