0

I am trying to create a gallery. Where many images will be created. Though I want my first image to be big[500 x 500 px] and rest of them [80 x 80px]. I want to change the large image src with the clicked imaged src. I have tried using ref. But its not working.

I am calling an api to get the images.

Currently I am trying with

 const imageRef = React.useRef<HTMLImageElement | null>(null);

 function handleImageClick(e: React.MouseEvent<HTMLImageElement>) {
    console.log(e.target)
    const target = e.target as HTMLImageElement
    imageRef.current!.src = target.src
  }

The return statement is

<Image
   ref={imageRef}
   src={imageRef.current?.src || thumbnailImage}
/>

From the smaller images list are as

{images.map((image: string, index: number) => (
    <Image
    onClick={handleImageClick}
    key={index}
    src={image}
/>
))}
2
  • I solved it with useState though. But if there is a useRef way of doing this. That will be great. Commented Dec 22, 2022 at 4:19
  • What version is nextjs? Check out this comment stackoverflow.com/a/74740631/4449475 Commented Dec 22, 2022 at 5:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.