Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the react-draggable not support on mobile platform?

Tags:

reactjs

My code is here.

The p-in-p button of the MediaPlayer triggers the MiniPlayer component.

And the react-draggable package is used in MiniPlayer component.

The top-left button works on the computer; however, it does not work in the mobile device.

When I remove the <Draggable> tag from the MiniPlayer.js, the top-left button works on mobile again.

How can I fix the problem?

like image 326
The KNVB Avatar asked Sep 18 '25 14:09

The KNVB


2 Answers

react-draggable works on mobiles. It seems onClick or onChange inside <Draggable> are disabled on mobiles (or on touch devices in general).

To make elements inside the drag component clickable, set as cancel the selector of those elements.

<Draggable cancel=".btn">
  <div>
  ...
  <button className="btn">click</button>
</div>

</Draggable>```
like image 134
wenzf Avatar answered Sep 21 '25 05:09

wenzf


react-draggable works on mobiles but it also disable onClick or any Clickable of all child elements of the draggable item, except onTouchStart and onTouchEnd. You can use cancel props but it also disable the ability to drag and drop.

Here my solution and more explain: "You can then handle the touchstart event to save the starting position of the finger and use it to calculate the distance to move when the user drags the div. When the touchend event is fired, checks if the travel distance is less than some threshold (e.g. 5px) to determine if the user is making a click call."

And here the code:

import React, { useState } from 'react';
import Draggable from 'react-draggable';

const DraggableDiv = () => {
  const [startX, setStartX] = useState(null);
  const [startY, setStartY] = useState(null);

  const handleTouchStart = event => {
    const touch = event.touches[0];
    setStartX(touch.clientX);
    setStartY(touch.clientY);
  };

  const handleTouchEnd = event => {
    const touch = event.changedTouches[0];
    const endX = touch.clientX;
    const endY = touch.clientY;
    const distance = Math.sqrt((endX - startX) ** 2 + (endY - startY) ** 2);
    if (distance < 5) {
      console.log('Click!');
    }
  };

  return (
    <Draggable>
      <a href="#" onTouchStart={handleTouchStart} onTouchEnd={handleTouchEnd}>
        <div>Draggable Div</div>
      </a>
    </Draggable>
  );
};

export default DraggableDiv;
like image 25
Huu Phong Nguyen Avatar answered Sep 21 '25 05:09

Huu Phong Nguyen