0

Hey Am using React select Custom component and In the dropdown Option am Adding 2 icons,and i want to add the onClick Event on that, the Problem is when i click the icon, the default onClick also get called and the default action also get executed in the background.

export const SvdSrchSelectOpt = (props : any) =>
{
  return (
    <components.Option {...props} >
      <Styld.Div >
        <div className="flex-auto w-full">{props.label}</div>
        <div className="container flex ml-auto justify-end">
          <Button variant='noBorder' onClick={props.onEdit} icon="writing-editing" className='max-w-35p justify-items-center'>
          </Button>
          <Button variant='noBorder' onClick={props.onDelete} icon="TrashMessaging" className='max-w-35p justify-items-center'>
          </Button>
        </div>
      </Styld.Div>
    </components.Option >
  );
};

i want if user Click on the Label then default onClick get execute but if user click on any of these icon then icon's Onclick get execute. Please help me in this Thanks In Advance

AYUB KHAN
  • 15
  • 4
  • What happens if you add either preventDefault() or stopPropagation to the onClick handlers for your icon buttons? – Tor Raswill Nov 17 '21 at 09:49

1 Answers1

0

The easiest way is to use event.stopPropagation inside the Icons functions. So something like:

function onEdit(event) => {
  event.stopPropagation();
  ...

But this means you won't be able to to catch the click anywhere else (for example you might have an open selector you might want to close when the page is clicked or something similar). Another pretty easy solution (and the option I would personally recommend) would be replacing e.stopPropagation() with e.preventDefault() + e.defaultPrevented

So basically you should add inside icons functions:

function onEdit(event) => {
  event.preventDefault();
  ...

and default onClick should have the condition. Something like:

function onClick(event) => {
  if(event.defaultPrevented) return
}

You can also see more about this topic here

Berci
  • 2,876
  • 1
  • 18
  • 28