Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle React onDoubleClick and single onClick for same element

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>
 }
like image 696
Sean Avatar asked Mar 09 '18 05:03

Sean


People also ask

How do you handle double click event in React?

To handle double click events in React:Add an onClick prop to the element. Use the detail property on the event object to get the click count. If the click count is equal to 2, handle the double click event.

How does react native detect double click?

Furthermore you can just add a custom code for implementing doubleclick in react native touchables. What you can do is to just save the count on click and clear the click counter after some seconds then trigger a funtion on onPress when it is clicked twice.

How do you use events in Reactjs?

Handling events with React elements is very similar to handling events on DOM elements. There are some syntax differences: React events are named using camelCase, rather than lowercase. With JSX you pass a function as the event handler, rather than a string.

How do you pass values to onClick React function?

In order to pass a value as a parameter through the onClick handler we pass in an arrow function which returns a call to the sayHello function. In our example, that argument is a string: 'James': ... return ( <button onClick={() => sayHello('James')}>Greet</button> ); ...


1 Answers

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>
}
like image 151
Sean Avatar answered Sep 23 '22 07:09

Sean