How can I create a Double Click Link in react?

1.4k Views Asked by At

I have a Draggable image link that opens the link in a new tab. The problem is that when the image is dragged it of course ends up clicking the link, when I don't want it to. So how can I make it so that the link only activates on a double click?

<Draggable>
    <div className="m-2">
      <a
        href={destination}
        rel="noreferrer"
        target="_blank"
        className="relative cursor-zoom-in w-auto hover:shadow-lg rounded-lg overflow-hidden transition-all duration-500 ease-in-out"
      >
        <img
          className="rounded-lg w-full"
          alt="user-post"
          src={urlFor(image).width(1000).url()}
        />
      </a>
    </div>
    </Draggable>
3

There are 3 best solutions below

1
On

due to the limitations of DOM's Click and double click events, it cannot detect the difference between a click and a double click.

You can still do this though by using a "Delay".

  let timer = 0;
  let delay = 200;
  let prevent = false;

  doClickAction() {
    console.log(' click');
  }
  doDoubleClickAction() {
    console.log('Double Click')
  }
  handleClick() {
    let me = this;
    timer = setTimeout(function() {
      if (!prevent) {
        me.doClickAction();
      }
      prevent = false;
    }, delay);
  }
  handleDoubleClick(){
    clearTimeout(timer);
    prevent = true;
    this.doDoubleClickAction();
  }
 <button onClick={this.handleClick.bind(this)} 
    onDoubleClick = {this.handleDoubleClick.bind(this)} > click me </button>
1
On
const navigate = useNavigate()
    
return (
        <Draggable>
            <div className="m-2">
              <button
                onDoubleClick={() => navigate('/link')}
                className="relative cursor-zoom-in w-auto hover:shadow-lg rounded-lg overflow-hidden transition-all duration-500 ease-in-out"
              >
                <img
                  className="rounded-lg w-full"
                  alt="user-post"
                  src={urlFor(image).width(1000).url()}
                />
              </button>
            </div>
            </Draggable>
    )
0
On

I switched to a button with a onDoubleClick function:

function here () {
       window.open(destination, '_blank');
     }