On button click i get event of child element

733 Views Asked by At

I am trying to get the event of button on clicking it. I have an image inside the button.

<button onClick={this.selectSubject} value="PHYSICS" className="button-blue"><img src={Magnet} />PHYSICS</button>

When i click on button i get event as

<button value="PHYSICS" class="button-blue"><img src="/static/media/magnet.d8028ed2.svg">PHYSICS</button>

But when i click specifically on image i get event of image tag as

<img src="/static/media/magnet.d8028ed2.svg">

Its expected behaviour should be that i get event of button element. Why this is happening.

2

There are 2 best solutions below

0
On BEST ANSWER

It looks like you are using event.target to get the clicked element. In this case target won't be button every time you click. It always refers to the element got the event fired upon.

I would suggest you to use event.currentTarget which will always be the element which is bound to the event.

0
On

You're clicking the image, so the image is the element where the onClick event is happening. This IS the expected behaviour, you clicked the image, not the button that contains it.

To prevent any click events happening on the image, you style the image element with CSS pointer-events property:

pointer-events: none;

This prevents any pointer events (click interactions included) on the image, and the button will now be the element returned for the event.

If you have several elements inside your button, it might be easier to style the button itself with:

button > * {
  pointer-events: none;
}

This will prevent any child elements of the button from being clicked.