How to Handle Double-Click Events in React

Need to handle a double-click event?

React makes it easy!

Here's how:

Handling double-click events in React

We can do it by leaning on our usual onClick prop.

We then check the detail property on the event to give us the click count so we can handle the case appropriately.

export default function DoubleClicker() {
  const handleClick = (event) => {
    if (event.detail === 2) {
      console.log("Single click");
    }
    // If the detail is `2` we handle our double click
    if (event.detail === 2) {
      console.log("✨ Double clicked ✨");
    }

    if (event.detail === 4) {
      console.log("Quadruple clicked");
    }
  };

  return <button onClick={handleClick}>Double click me</button>;
}

So if we wanted to only handle double-clicks and ignore other patterns it's easy - just keep the if statement where we check event.detail === 2.

export default function DoubleClicker() {
  const handleClick = (event) => {
    // If the detail is `2` we handle our double click
    if (event.detail === 2) {
      console.log("✨ Double clicked ✨");
    }
  };
  return <button onClick={handleClick}>Double click me</button>;
}

As you can see, it's pretty straightforward, thanks to the details property.


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

Reactjs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.