Limiting click event to only Image component in Next.js

Is there a way to trigger a click event only on the image itself, rather than the entire parent div? When setting width and height for the parent div, the click event seems to encompass the entire area.

For instance, if the image is 600 pixels wide by 300 pixels high, clicking outside the image but within the parent still triggers the click event.

<div
  style={{ width: 600, height: 600 }}
  className="image-item bg-gray-200 w-9/12 h-auto relative"
>
  <div
    onClick={(e) => handleTags(e)}
    className=""
    ref={imageWrapRef}
  >
    <Image
      className=""
      src={image["data_url"]}
      alt=""
      layout="fill"
      objectFit="contain"
    />
  </div>
</div>

https://i.sstatic.net/azn52.jpg

Even though there is space above and below the image, those areas remain clickable. I just want the click action to apply to the image only.

Here's a screenshot of the inspected element in the code:

https://i.sstatic.net/kIGXn.png

You can also view a functional codesandbox here: https://codesandbox.io/s/proud-rain-d51sv?file=/pages/index.js

Answer №1

If you encounter this problem, make sure to define the width and height of the image before displaying it.

One helpful solution I found was to utilize onLoadingComplete, with more information available here: Next.js Image component props onLoadingComplete not working?

This approach allowed me to specify the width and height as follows:

<Image
  onLoadingComplete={(e) => handleImageLoad(e)}
  className=""
  src={data2blob(image)}
  alt=""
  width={imageWidth}
  height={imageHeight}
  layout="responsive"
  objectFit="contain"
/>

The function handleImageLoad looked like this:

const handleImageLoad = (e) => {
  setImageWidth(e.naturalWidth);
  setImageHeight(e.naturalHeight);
};

Note:

I initially faced a challenge due to the order of operations (uploading the image before determining its dimensions). To address this, I had to set the initial width and height values:

const [imageWidth, setImageWidth] = useState(0);
const [imageHeight, setImageHeight] = useState(0);

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

The div is not displaying the background image as intended

.cover-image { margin-bottom: 0px; height: 350px; color: white; text-shadow: black 0.3em 0.3em 0.3em; } <div class="cover-image" style="background: url('~/images/hdpic.jpg') no-repeat; background-size:cover"> </div> I&apo ...

Using callback functions to initiate server actions

Currently, I am diving into server actions within the Next.js 14 app router. Server actions are mainly used for making post requests to the server. But, I am curious if there is a way for server actions to trigger a function on the client side. My goal is ...

What is the best way to save a large quantity of objects to a server using ajax and php?

Imagine a scenario where I have a page containing 100 objects, each around 700 bytes when converted to json format. When it comes to saving these objects to the php based controller, there are several options available to me. Option 1: For each object ( ...

Every time I utilize SessionProvider from next/auth/react, I encounter an error that states: "TypeError [ERR_INVALID_URL]: Invalid URL."

While working on my application in Next.js, I decided to incorporate NextAuth into the project. However, when attempting to use SessionProvider as instructed in the documentation, I encountered an error message stating: "TypeError [ERR_INVALID_URL]: Invali ...

The Date.UTC function is not providing the correct output

While attempting to change Unix timestamps into a more understandable format, I used Date.UTC(2017,09,23);. When running this code, it returned 1508716800000. However, upon verifying on the website , the displayed result showed October 23, 2017 instead o ...

How about incorporating two subtly tilted SVGs for a creative twist on navigation backgrounds?

I am in the process of designing the navigation menu for my website and I have a specific vision in mind. I want to create a unique background using two rectangular SVGs that are slightly rotated off axis and overlapping each other, with their edges extend ...

Button to expand or collapse all sections in Ant Design Collapse component

Is there a way to create a button that can expand or collapse all tabs in an ant.design Collapse component? I attempted to modify defaultActiveKey but it seems like this can only be done during page rendering. If possible, could someone share a code snip ...

creating an animated loop within an Angular template

How can we display a dynamic loop in Angular template using an array of object data? [ { "name": "name", "text": "text", "replies": [{ "name": "Reply1", "t ...

The MUI Time picker fails to display the correct time value in the input field with proper formatting

My primary goal is to implement a MUI time picker with yup validation and react-hook-form. However, I am encountering an issue where the selected time from the time picker is not being updated in the text field as expected. https://i.sstatic.net/LVkgK.png ...

Is there a way to create an image gallery layout similar to Pinterest using CSS?

I am currently developing a dynamic PHP gallery that will feature thumbnails with the same width but varying heights. These thumbnails will be arranged from left to right, so I would prefer not to use a traditional five-column layout. I suspect that achiev ...

To implement a server-side 301 redirect to force the URL to go to www in React.js using Next.js

I am currently facing an issue with routing my website to redirect to the www server side. Specifically, when a user visits my website example.com, I want to redirect them to www.example.com. To achieve this, I have implemented a redirect using Next.js in ...

What is the best way to transfer properties to a different component using the onClick event triggered by an element generated within the map function?

I am currently working on an application using react to retrieve data from a mongodb database. Within one of the components, called Gallery, I have integrated a map function to display a list of items. My goal is to implement an onClick event for each elem ...

Solution: Resolve clientY scrolling issue within an HTML document

I am facing an issue with the positioning of my context menu. When I right-click and scroll down, the menu does not maintain its regular position. Instead of appearing to the right of the mouse cursor when stationary, it moves below the cursor based on how ...

Navigating to an Element in React's Document Object Model

Using React 16.4, I am faced with the need to scroll to a specific DOM element within the application. Since refs are deprecated in React, I am on a quest to find the most elegant solution for this problem. However, I find it challenging to come up with a ...

Utilizing React JS: Displaying or Concealing Specific Components Based on the URL Path

Is there a way to dynamically change the navbar items based on the URL without having separate navbar components for each side? My current navbar design features 3 links on the left side and 3 links on the right, but I want to display only one side at a ti ...

Converting PHP arrays into JavaScript arrays with the help of json_encode()

Is there a way to pass an array from PHP to the JavaScript function console.log()? I'm currently simulating a database and need help with this specific task. Despite not having an array declared in my code, I attempted to use the .getJSON() function w ...

Receiving JSON in a C# web service: A step-by-step guide

I created a JSON string using jQuery and now I want to send it to a C# web API controller. Here is an example of the JSON object: {"Name":"","Type":"4","Meals":["2","3"],"Excludes":["Beef","Chicken"]} I attempted to send it with a URL structure like thi ...

What is the best way to automatically create a PDF file that includes interactive JavaScript charts?

My goal is to create a word document or PDF containing charts from various JavaScript chart libraries. I've successfully implemented these libraries on websites, but now I want to include them in my documents as well. My initial attempt involved usin ...

Semantic-UI-react sticky sidebar

I have searched extensively on Google, reviewed semantic ui's documentation and issues page, and also checked Stack Overflow but could not find a solution to my problem. My question is related to Semantic-ui-react - how can I create a sidebar with fi ...

What is the best way to use jQuery to apply CSS only to elements with a specific attribute set?

Currently, I am attempting to utilize jQuery to apply specific CSS styles to elements, but only those that possess a particular attribute. The rationale behind not resorting solely to CSS is due to the immense amount of content on the site, making it impr ...