Search code examples
reactjseventsevent-bubbling

React onClick event firing for child element


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.


Solution

  • 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.