Home > Back-end >  CurrentTarget and target issue in React
CurrentTarget and target issue in React

Time:10-29

I am using map in one of the component in React -

{ iconName.map(icon => (
       <button onClick={clickHandler} key={icon.id} className='nav__tab'>
           <Tabs iconName={icon.name} iconUrl={icon.src}/>
       </button>

))}

And in the Tabs component, I have

<div className='tabs'>
  <div>{ iconUrl }</div>
  <span className='tabs__name'>{iconName}</span>
</div>

And on the UI, it looks like this -

[(https://img.codepudding.com/202210/299c64916e67402a9e1e3a7df535d1ec.png)

The problem - Whenever I click on any button, I want to differentiate which button is clicked. Like when user clicks on Button1, I want to know that button1 is clicked and so on. I am not getting anything inside event on clickHandler function to differentiate the buttons.

I checked event.target inside the event, but when I click on SVG icon, it consoles null. And when I click on the text like button1, button2 it gives me the desired result. Only problem is when I click on SVG icons.

CodePudding user response:

It is an issue of the target element being SVG, you can use closest method, but the easier way, you can pass the icon as a second parameter, and you will get the clicked icon.

{ iconName.map(icon => (
       <button onClick={(e) => clickHandler(e, icon)} key={icon.id} className='nav__tab'>
           <Tabs iconName={icon.name} iconUrl={icon.src}/>
       </button>

))}

CodePudding user response:

will need to pass the event to the function know wich is the target. try:

{ iconName.map(icon => (
       <button onClick={(e) => clickHandler(e)} key={icon.id} className='nav__tab'>
           <Tabs iconName={icon.name} iconUrl={icon.src}/>
       </button>

))}

You can pass the icon like second parameter to the function too.

CodePudding user response:

You have minimum 2 options here to get what you want:

  1. Instead of checking if the clicked event matches a specific selector, you can check if it occurred within a selector using the closest() method.
  2. You can disable clicking on SVGs so that the event fires on the parent button instead of the SVG and it’s child elements. svg { pointer-events: none;}

For more information, you can refer: Detecting click events on SVGs with vanilla JS event delegation.

  • Related