Handle React onDoubleClick and single onClick for same element

16.1k Views Asked by At

When I add a single onClick event to an element as well as an onDoubleClick event to the same element, the single click is triggered on the double click as well. I'd like to seperate it out so only one event is fired for single or double. I found some examples in Jquery, but I wanted a clean function for React.

 handleClick = () => {
   console.log('only fire click')
 }

 handleDoubleClick = () => {
   console.log('only fire double click')
 }

 render () {
  return <Element 
             onClick={evt => this.handleClick}
             onDoubleClick={evt => this.handleDoubleClick} 
         ></Element>
 }
2

There are 2 best solutions below

0
On BEST ANSWER

Based on the other snippets I found for jquery, I created this simple function to spawn the correct event based on the clicks. Hopefully this helps other React'ers.

componentWillMount = props => {
  this.clickTimeout = null
}

handleClicks = () => {
  if (this.clickTimeout !== null) {
    console.log('double click executes')
    clearTimeout(this.clickTimeout)
    this.clickTimeout = null
  } else {
    console.log('single click')  
    this.clickTimeout = setTimeout(()=>{
    console.log('first click executes ')
    clearTimeout(this.clickTimeout)
      this.clickTimeout = null
    }, 2000)
  }
}

render () {
  return <Element 
             onClick={evt => this.handleClicks}
         ></Element>
}
1
On

I hope below code will help you to fire single and double clicks,

constructor(props){
  super(props);
  this.clickCount = 0;
  this.singleClickTimer = '';
}

singleClick = () => {
    console.log('only fire click')
}

handleDoubleClick = () => {
    console.log('only fire double click')
}
handleClicks(){
    this.clickCount++;
  if (this.clickCount === 1) {
    this.singleClickTimer = setTimeout(function() {
      this.clickCount = 0;
      this.singleClick();
    }.bind(this), 300);

  } else if (this.clickCount === 2) {
    clearTimeout(this.singleClickTimer);
    this.clickCount = 0;
    this.handleDoubleClick();
  }
}
render () {
  return <Element 
             onClick={() => this.handleClicks()} 
         ></Element>
 }

For your reference, https://jsfiddle.net/69z2wepo/130223/