Hi I am trying to implement a modal with slideshow for next images. I am using unsplash api to fetch images.
The problem I am facing is whenever I am trying to click a random image in a grid, it shows only the first image in Modal.
This is my implementation for setting up the images and modal functionality. I am using the react-modal package for setting up my Modal.
imageList = Array of objects containing image data
url = An object containing image url.
export default function Images({ imageList, url, id }) {
const [modalIsOpen, setModalIsOpen] = useState(false);
const [current, setCurrent] = useState(0);
const length = imageList.length;
function openModal() {
setModalIsOpen(true);
}
function closeModal() {
setModalIsOpen(false);
}
const nextSlide = () => {
setCurrent(current === length - 1 ? 0 : current + 1);
};
const prevSlide = () => {
setCurrent(current === 0 ? length - 1 : current - 1);
};
if (!Array.isArray(imageList) || imageList.length <= 0) {
return null;
}
return (
<div>
<img onClick={openModal} key={id} src={url.urls.thumb} alt='' />
<Modal
ariaHideApp={false}
closeTimeoutMS={200}
style={customStyles}
isOpen={modalIsOpen}
onRequestClose={closeModal}
contentLabel='Image modal'
>
<AiOutlineArrowLeft
className='left-arrow'
onClick={prevSlide}
/>
<AiOutlineArrowRight
className='right-arrow'
onClick={nextSlide}
/>
{imageList.map((image, id) => {
return (
<div
className={
id === current ? 'slide active' : 'slide'
}
key={id}
>
{id === current && (
<img
alt=''
className='image'
src={image.urls.small}
/>
)}
</div>
);
})}
</Modal>
</div>
);
}
Thanks in advance for the help.
You should set the current-image-index by clicking the img.
<img onClick={()=>openModal(id)=} key={id} src={url.urls.thumb} alt='' />
function openModal(id) {
setCurrent(id);
setModalIsOpen(true);
}
or use the id / index from the props
const [current, setCurrent] = useState(id);