I have a list of images to display thumbnails. On top of that, for each image, I want to click it to show the image on the full size.
To achieve this, I use Modal
and useDisclosure()
from @nextui-org/react
. Below is my code:
const { isOpen, onOpen, onOpenChange } = useDisclosure();
<Card className="" isPressable onPress={onOpen}>
<CardHeader className="flex-col items-start">
<p className="text-tiny uppercase font-bold">id:12345678</p>
<small className="text-default-500">date:2024-01</small>
<h4 className="font-bold text-large">name</h4>
</CardHeader>
<CardBody className="overflow-visible">
{/* <a href="https://www.baidu.com" target="_blank"> */}
<Image
alt="Card background"
className="object-cover rounded-xl"
src="/patent/1.png"
height={270}
width={270}
/>
{/* </a> */}
</CardBody>
</Card>
<Modal isOpen={isOpen} onOpenChange={onOpenChange} size="5xl" scrollBehavior="outside" id="modal">
<ModalContent>
{() => (
<>
<ModalBody>
<Image
alt="Card background"
className="object-cover rounded-xl"
src="/patent/1.png"
height={2000}
width={2000}
/>
</ModalBody>
</>
)}
</ModalContent>
</Modal>
My question is, since I have a list of images, whose length is variable. It is not wise or elegant to hard-code a list of corresponding useDisclosure()
How can I auto create useDisclosure for each image?
2
Answers
Problem :
Solution :
Code :
I have kept code as minimum as possible (you may make necessary changes as needed)
Explaination :
Images
array contains object with image details,const [ClickedImg, SetClickedImg] = useState(null)
is used to store clicked image detailsThen Card is mapped using
Images
array, & details are assigned in it.onPress
function does two things sets stateSetClickedImg(v)
& then opens Modal by callingonOpen()
.When Card is clicked, Modal opens & shows details using
ClickedImg
state.Don’t forget to uncomment
use client
line if using NextJS.I did something similar, but I’ve refactor in your code. Hope this helps.
This is an example of how to use.
How to use in your other functions