When the onClick event is triggered, Next.js will dynamically render a new

Looking to display a larger version of an image in a new div upon click? Here are four different methods I've tested:

  1. 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}/>
  1. 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' />
  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>
  1. 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!

Answer №1

If you're looking to implement a zoom effect for your images, consider the following approach:

First, set the hook in your code:

[zoomImage, setZoomImage] = useState(false)
<Image src={'/gafas.png'} width={150} height={150} alt='Gafas 1' onClick={() => setZoomImage(true)}/>

// Zoomed image display
<div className={`${zoomImage ? 'block' : 'hidden'} 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>

This code snippet essentially instructs Next.JS to toggle the zoomImage variable to true upon clicking the image. As a result, the larger version of the image that is initially hidden will be displayed with the 'block' property (assuming you are using tailwindcss).

Answer №2

Big thanks to @Atena Dadkhah for providing a perfect solution!

In my project, I had multiple images to work with, so the final code ended up like this:

function expandImage(e) {
    setExpanded(true);
    let img = document.getElementById('largerImage'),
        src = e.target['data-loaded-src'];
    img['src'] = src;
  }

Followed by several image instances like this:

<Image src={'/gafas.png'} width={150} height={150} alt='Gafas 1' onClick={expandImage} className='cursor-zoom-in' />

Next, the hidden container:

<div className={`${expanded ? 'flex' : 'hidden'} w-screen h-screen fixed justify-center items-center`}>
  <div className='w-9/12 h-5/6 bg-slate-200 flex justify-center items-center relative'>
    <Image id='largerImage' fill={true} />
  </div>
</div>

I still need to implement the functionality for closing the container, but that shouldn't be too difficult to include.

Once again, many thanks! :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Are you experiencing issues with the cross-origin request failing in react-map-gl?

While setting up a map in react-map-gl and providing my access token, I encountered the following console error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://events.mapbox.com/events/v2?access_token= ...

Discovering the presence of two values within a single object array with the power of JavaScript

My challenge involves handling an array containing flight details such as origin, destination, and ticket cost. I am attempting to display the specific flight details for a given origin-destination pair. For instance: if the user chooses Bangalore as the o ...

Is it necessary for the Jquery Component to return false?

I'm currently working on developing a jQuery module using BDD (Behavior-driven development). Below is the code snippet for my component: (function($) { function MyModule(element){ return false; } $.fn.myModule = function ...

Sending Information within Controllers with AngularJS

I have a unique scenario in my application where I need to pass input from one view to another. I have set up a service as shown below: .service('greeting', function Greeting() { var greeting = this; greeting.message = 'Default&ap ...

"Jesting with JavaScript: Thou shall be warned, for undefined does

While running my unit tests with jest, I encountered an error: TypeError: Cannot read properties of undefined (reading 'getVideoTracks') Can anyone provide suggestions on how to properly test the following line using jest? [videoTrack] = (await ...

The active class in the Bootstrap carousel is not updating when trying to change

I am struggling to make the Twitter Bootstrap carousel function properly. Although the slides automatically change after the default timeout, the indicators do not switch the active class, resulting in my carousel failing to transition between slides. Ini ...

Having trouble getting my AngularJS directive with a number in the name to function properly

Check out my code snippet: app.directive('3dPlansSlider', function(){ return { controller: 'projectCtrl', restrict: 'E', templateUrl: 'views/3dPlansSlider.html', link: function(scope, element, attr ...

The Vue template syntax utilizes double curly braces for incrementing values within must

Embarked on learning Vue.js recently and I am intrigued by the unusual behavior in my simple code. I cannot seem to figure out what is going wrong. I am attempting to increment a counter inside mustache syntax, but something strange is happening with this ...

File uploading from Angular to Node.js backend encountering issues with reading file data

I'm currently using Angular file upload with Laravel Lumen in the past for the backend, but now I've switched to Node and I'm having trouble retrieving the file contents after an upload. ANGULAR FRONT END $scope.upload = Upload.upload({ ...

Issues Arising from Integration of AWS Amplify with NextJS and Streaming API Response

I am using NextJS with AWS Amplify and have implemented a streaming API call to handle long processing times. While this works well locally, I am facing issues with streaming when deploying on AWS Amplify as it exceeds the 30 seconds timeout limit. Any su ...

The comparison between 'MutableRefObject<string | null>' and 'string' will never be true, as they do not share any common types. Error code: TS2367

Struggling with a React and TypeScript issue I have stored the email and password in state variables const emailRef = useRef<string | null>(null); const passwordRef = useRef<string | null>(null); This is how I set them: const onEmailChange = ...

What circumstances allow @Inject to be optional in Angular?

My Angular service is simple yet causing errors. Here's the code snippet: // service.ts export class SimpleService { // ... } // component.ts @Component({ selector: 'my-component', templateUrl: 'components/mycomp/mycomp.ht ...

Executing the command `npm run jshint` yields the error message `script not found: jshint`

Currently, I'm attempting to run jshint on a few javascript files. However, I am encountering an issue where the local npm install of jshint is not functioning as expected. Upon checking, the package is indeed present: $ npm list --depth=0 <a hre ...

The two CSS classes are styled with different border-color values, but only one is being applied correctly

My goal is to modify the border color of a textarea using jQuery. Previously, I achieved this by using .css("border-color","rgb(250,0,0)"), and it was working perfectly. However, I have now been advised against using CSS directly in JavaScript and told to ...

Guide on Redirecting Response to a File using Co-Request module with NodeJs

I am utilizing Co-Request from this repository to fetch a Zip file from a URL, and the code I have for fetching it is as follows: The current code works fine. However, I'm facing difficulty in saving the response Zip file to an actual file. var co = ...

Mapping the table by the header and the first cell in each row to be filled with data from a JSON

As I utilize PHP to echo JSON array inline, my goal is for JavaScript/jQuery to populate a table based on this data. The HTML table structure looks like this: <table> <thead> <tr> <th>Time</th> <th dat ...

Combine the foundation navigation with bootstrap in order to create a seamless

Has anyone figured out a way to mimic the "top bar" functionality in Foundation (where child menu items slide to the left on mobile) within the Bootstrap framework? I really appreciate how Foundation handles the mobile navigation sliding for child items, ...

The Angular Material dialog fails to display content when triggered within an event listener in Google Maps

Within my project, I am utilizing Angular 6.0.6 and Angular Material 6.3.0. One issue I have encountered is with a dialog component that I have added to the entryComponents in the app module. Strangely, when I attempt to open this dialog within the rightcl ...

Distinguishing each unique JavaScript property within an array of objects

I've been struggling with this problem for quite some time. I have an array of objects, focusing on the "00" object at the moment, and I am trying to group together the bestScore properties in a specific way: .. User Group apple .. User Group ba ...

Utilizing repeated directives within a single controller in Angular

Currently, I am in the process of developing a webpage that utilizes Highcharts to display some data. To ensure reusability, I have encapsulated the desired chart within a directive. 'use strict'; angular.module('statisticsApp') .dir ...