Looking to display a larger version of an image in a new div upon click? Here are four different methods I've tested:
- Render div on Click
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}/>
- Custom component
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' />
- Existing div onClick remove hidden class
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>
- This one DID work but I'm loosing nextjs image optimization
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} />
While all approaches show the log in the console, only approach 4 successfully displays the new div. Is this the best method or is there a more preferred way using the Image component? Share your thoughts!