Home > Software design >  React onClick event firing for child element
React onClick event firing for child element

Time:06-08

Click Handler.

const handleClick = (event) => {
    console.log(event.target);
  }

Return.

{ menu.map((menuItem, index) => (
      <div onClick={handleClick}>
          <div>{menuItem.text}</div>
          <img src={menuItem.image} /></div>
          ))
        }

My console tells me that the event.target is the IMG element instead of the DIV. Why is this happening and how can I lock the event to the parent DIV? Do I just have to write logic to look at the IMG parent element?

Thanks y'all.

CodePudding user response:

this is because Bubbling and capturing. event.target is the “target” element that initiated the event. it's the event that you clicked on it and in this case, it was an image. I think you can get div by event.currentTarget because the handler runs on it.

CodePudding user response:

Not sure about your code, but forcing the scope to the one of the div should work as well:

const handleClick = (event) => {
    console.log(event.target);
  }

{
   menu.map((menuItem, index) => (
      <div onClick={evt => handleClick(evt)}>
          <div>{menuItem.text}</div>
          <img src={menuItem.image} /></div>
          ))
        }

Which is basically what you had, but I edited <div onClick={evt => handleClick(evt)}>.

  • Related