I have several image thumbnails in my component that when clicked open a modal with Swiper.js displaying a carousel with the larger images and it's working ok. but I needed to find a way to open directly to the image that the user clicks on, because right no matter which one the user clicks on, it's always opening the first, from the beginning.
"use client"; import Navbar from "@/app/components/navbar"; import Image from "next/image"; import { projects } from "../../data/projects"; import { useState } from "react"; import { Swiper, SwiperSlide } from "swiper/react"; import { Navigation, Pagination } from "swiper/modules"; import "swiper/css"; import "swiper/css/navigation"; import "swiper/css/pagination"; import "swiper/css/thumbs"; const ProjetoDetalhes = ({ params }: any) => { const proj = projects.find((proj) => proj.id.toString() === params.id); const [modalIsOpen, setModalIsOpen] = useState(false); const [selectedImageIndex, setSelectedImageIndex] = useState<number | null>( null ); const openModal = (index: number) => { setSelectedImageIndex(index); setModalIsOpen(true); }; const closeModal = () => { setSelectedImageIndex(null); setModalIsOpen(false); }; return (<> ...<div className="flex flex-wrap gap-4 mt-12 w-full justify-center sm:justify-start"> {proj?.fotos.map((foto, index) => (<div key={index} onClick={() => openModal(index)} className="grid grid-cols-2 h-44 w-44 relative"><Image src={foto} alt={`Imagem ${index + 1}`} fill className="cursor-pointer object-cover" /></div> ))} {/* modal, swiper */} {modalIsOpen && selectedImageIndex !== null && (<div className="fixed inset-0 flex items-center justify-center min-h-screen" onClick={closeModal}><div className="absolute inset-0 bg-black opacity-75"></div><div className="relative" onClick={(e) => e.stopPropagation()}><button onClick={closeModal} className="absolute top-4 right-4 text-white text-3xl z-50">×</button><div className="overflow-hidden"><div className="container"><Swiper navigation pagination={{ type: "fraction" }} modules={[Navigation, Pagination]} className="md:h-[50em] md:w-[80em] h-96 w-96"> {proj?.fotos.map((foto, index) => (<SwiperSlide key={index}><div className="flex h-full w-full items-center justify-center"><Image src={foto} alt={`Imagem ${index + 1}`} className="block object-contain h-full w-full" fill /></div></SwiperSlide> ))}</Swiper></div></div></div></div> )}</div></div></main></> );};export default ProjetoDetalhes;