Last updated: Apr 6, 2024
Reading time·1 min
To handle double-click events in React:
onClick
prop to the element.detail
property on the event
object to get the click count.export default function App() { const handleClick = event => { console.log(event.detail); 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; } } }; return ( <div> <div> <button onClick={handleClick}>Double click</button> </div> </div> ); }
We added an onClick
prop to a button element, so every time the button is
clicked, the handleClick
function is invoked.
The detail
property on the event
object provides the current click count for click
events.
switch
statement will run the code for case 1 and case 2.If you don't want to handle any of the other cases, you can use an if
statement to check if event.detail
is equal to 2
.
export default function App() { const handleClick = event => { if (event.detail === 2) { console.log('double click'); } }; return ( <div> <div> <button onClick={handleClick}>Double click</button> </div> </div> ); }
The handleClick
function explicitly checks if the current click count is equal
to 2.
If you only need to handle double-click events, this solution should be sufficient.