I have an image and I want to create a new div (on click) with a larger version of the same image.
I tried four methods:
function zoom_img (event) { console.log(event.target); console.log(event.target['data-loaded-src']) const src = event.target['data-loaded-src'] return ( <div className='w-screen h-screen fixed flex justify-center items-center'> <div className='w-9/12 h-5/6 bg-slate-200 opacity-50'> <Image src={src} fill={true} /> </div> </div> ) } ... <Image src={'/gafas.png'} width={150} height={150} alt='Gafas 1' onClick={zoom_img}/>
function Glasses ({src, height, width, alt}) { function enlrg() { console.log(src); return ( <div className='w-screen h-screen fixed flex justify-center items-center'> <div className='w-9/12 h-5/6 bg-slate-200 opacity-50'> <Image src={src} fill={true} /> </div> </div> ) } return ( <Image src={src} width={width} height={height} alt={alt} onClick={enlrg} /> ) } ... <Glasses src={'/gafas.png'} width={150} height={150} alt='Gafas 1' />
function Glasses2 ({src, height, width, alt}) { function enlrg() { console.log(src); let x = document.getElementById('temp'); x.classList.remove('hidden'); x.classList.add('flex'); } return ( <Image src={src} width={width} height={height} alt={alt} onClick={enlrg} /> ) } ... <Glasses2 src={'/gafas.png'} width={150} height={150} alt='Gafas 1' /> <div id='temp' className='w-screen h-screen fixed hidden justify-center items-center'> <div className='w-9/12 h-5/6 bg-slate-200 opacity-50'> <Image src={'/gafas.png'} fill={true} /> </div> </div>
function zoom_img (event) { console.log(event.target); console.log(event.target['data-loaded-src']) const src = event.target['data-loaded-src'] const new_cont = document.createElement('div'); const new_div = document.createElement('div'); const main = document.getElementById('main'); new_cont.classList.add('w-screen', 'h-screen', 'fixed', 'flex', 'justify-center', 'items-center'); new_div.classList.add('w-9/12', 'h-5/6', 'bg-slate-200', 'opacity-50'); // add img tag here new_cont.appendChild(new_div); main.appendChild(new_cont); } ... <Image src={'/gafas.png'} width={150} height={150} alt='Gafas 1' onClick={zoom_img} />
In every method I can see the logs in the console, but only in method 4 I can see the new div.
Is method 4 the only correct way? I'd prefer to use an image component if possible. What do you think?
Thank you so much @Atena Dadkhah. Your answer is very valid.
In the project, there is not one but a bunch of images, so the final code looks like this:
Then a bunch of images like this:
Then the hidden div:
It still lacks the behavior of closing the div, but this should be easy to add.
again. Thanks:)
You could try something like this:
Set hook:
In this code you are essentially telling Next.JS to change the variable
zoomImage
to true whenever the user clicks on the image, so the larger image that is hidden by default will Has a display block. (I guess you are using tailwindcss)