I use react-modal in next.js
I can close my modal clicking on the x button, but i want to be able to close it when i press outside of the modal. I searched I found the property shouldCloseOnOverlayClick={true}
, but it doesn't make any difference. If you need more details or code I will give it .
this is my modal:
import React from "react";
import Modal from "react-modal";
import Image from "next/image";
import { XCircleIcon } from "@heroicons/react/24/outline"
Modal.setAppElement("html"); // Set the root element for accessibility
interface ImageViewerModalProps {
isOpen: boolean;
onClose: () => void;
imageUrl: string;
}
const ImageViewerModal: React.FC<ImageViewerModalProps> = ({
isOpen,
onClose,
imageUrl,
}) => {
return (
<Modal
isOpen={isOpen}
onRequestClose={onClose}
contentLabel="Full Image Viewer"
overlayClassName="modal-overlay"
shouldCloseOnOverlayClick={true}
className="modal-center z-30 flex flex-col items-center bg-secondary p-5 drop-shadow-lg rounded-xl"
>
<div className="w-full flex justify-end mb-5">
<XCircleIcon className="w-7 h-7 text-primary cursor-pointer" onClick={onClose}/>
</div>
<div className="w-full h-full overflow-hidden">
{/* Set a maximum width and height for the image container */}
<Image
src={imageUrl}
alt="Full Image"
quality={100}
className="modal-image w-full h-full object-cover"
/>
</div>
</Modal>
);
};
export default ImageViewerModal;
and this is where I use it
<SwiperSlide>
<Image
src={Background}
alt="Thumbnail"
quality={100}
placeholder="blur"
className="cursor-pointer"
onClick={() => openModal(Background)}
/>
</SwiperSlide>
also
...
</Swiper>
{isModalOpen &&
(<ImageViewerModal
isOpen={isModalOpen}
onClose={closeModal}
imageUrl={selectedImageUrl}
/>)}
I have the function here:
const [isModalOpen, setIsModalOpen] = useState(false);
const [selectedImageUrl, setSelectedImageUrl] = useState('');
const openModal = (imageUrl: any) => {
setIsModalOpen(true);
setSelectedImageUrl(imageUrl);
};
const closeModal = () => {
setIsModalOpen(false);
};
Ok, I found the problem guys! And i will put it here for anyone who has the same problem. The problem was here overlayClassName="modal-overlay"
the css for modal-overlay was broken , i changed it and now it's all good. here is the css
.modal-overlay {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5); /* Semi-transparent background */
z-index: 10; /* Ensure it's above other content */
}