I have the following code on this StackBlitz:
https://stackblitz.com/edit/react-vmstl9
import React from 'react';
import './style.css';
export default function App() {
return (
<div>
<h1>Try on Google Chrome Desktop</h1>
<p>Open the console log to see how the event gets triggered.</p>
<p>The event should not get triggered if there is a long click.</p>
<img
src="https://via.placeholder.com/200.png/09f/fff"
onClick={() => {
console.log('You clicked me!');
}}
/>
</div>
);
}
I need the click event to get triggered only if a normal click happens.
Currently if I click the image and holds the click for 2 seconds, the event still triggers. I need to prevent that.
Any idea on how to achieve that?
Thanks!
CodePudding user response:
I found this article on Stack Overflow found here
const myComponent = () => {
let clickHoldTimer = null;
const handleMouseDown = () => {
clickHoldTimer = setTimeout(() => {
//Action to be performed after holding down mouse
}, 1000); //Change 1000 to number of milliseconds required for mouse hold
}
const handleMouseUp = () => {
clearTimeout(clickHoldTimer);
}
return (
<div onm ouseDown={handleMouseDown} onm ouseUp={handleMouseUp} />
)
}
CodePudding user response:
you can do this hacks by get holder Time
https://stackblitz.com/edit/react-d1txdm
export default function App() {
let holdTimer;
return (
<div>
<h1>Try on Google Chrome Desktop</h1>
<p>Open the console log to see how the event gets triggered.</p>
<p>The event should not get triggered if there is a long click.</p>
<img
src="https://via.placeholder.com/200.png/09f/fff"
onClick={(e) => {
if (holdTimer > 1000) return;
else console.log('normal click');
}}
onm ouseDown={() => {
holdTimer = new Date().getTime();
}}
onm ouseUp={() => {
let endHolder = new Date().getTime();
holdTimer = endHolder - holdTimer;
}}
/>
</div>
);