0

I have been stuck that how we can add different click events on a single element. for that, I am adding my scenario that what I want to achieve.

So the scenario is I want to add two events on my button 1st is onClick={} 2nd is onDoubleClick={} and on both I am performing different actions. but when I add both events it calls every time the single onClick event, which means if I clicked twice it call two times onClick and one time onDoubleClick event where i just want to call only onDoubleClick event when I click twice.

Note: i want to implement this in react application.

here is my code of that button which has both onClick and onDoubleClick envets

<Button type="primary" className='btn btn-secondary' 
 onClick={() => console.log("once clicked")}
 onDoubleClick={() => console.log("twice clicked")} > >
       Two Events call        
</Button>

Output: [Output of clicking button twice][1] [1]: https://i.stack.imgur.com/3zcIk.png

Abidullah
  • 159
  • 3
  • 13
  • 1
    Does this answer your question? [onClick works but onDoubleClick is ignored on React component](https://stackoverflow.com/questions/25777826/onclick-works-but-ondoubleclick-is-ignored-on-react-component) – Sajeeb Ahamed Aug 01 '22 at 07:27
  • No, it seems that the question is the same but the usage and scenario are different, where he used to alert in both events, and alerts are prompted after the first click and didn't allow us to trigger the second event which is onDoubleClick. – Abidullah Aug 01 '22 at 07:43

1 Answers1

0

You can use event.detail to check clicks onClick

const clickHandler = event => {
    switch (event.detail) {
      case 1: {
        console.log("single click")
        break
      }
      case 2: {
        console.log("double click")
        break
      }
      case 3: {
        console.log("triple click")
        break
      }
      default: {
        break
      }
    }
}
...
<button onClick={clickHandler} >click me</button>

but first click will be used every time(and second for every 3click) so make sure you cleared it for 2 or 3 click. It's possible when you use debounce. hope this will help you

Ipa Stor
  • 158
  • 1
  • 5
  • It has the same issue as I am facing in my code, **when we click the button twice it prints "single click" and then prints "double click"**. – Abidullah Aug 01 '22 at 07:51
  • sorry, I haven't read your question right... I edited and the issue is to use debounce. the logic is to give react a delay(e.g. 1 second) to count clicks and then trigger what you need. i put the link there to the post where you can check only 1 click triggers. – Ipa Stor Aug 01 '22 at 07:55