Detecting click vs drag
I have a use-case in which the draggable element can either be dragged around or clicked to begin editing. Is there a way to detect a single click versus a drag motion?
Actually this fork https://github.com/STRML/react-draggable has an added handler for onMouseDown so was able to utilise that and the existing handlers to detect drag vs click.
Does anyone else have a solution for detecting click vs drag that doesn't involve using a fork?
Thanks very much!
Okay, I figured out what was going wrong thanks to: https://github.com/mzabriskie/react-draggable/issues/73
The trick is to differentiate between onDrag and and onClick, instead of onDragStart and onClick (like I was doing).
Hope this helps someone else :)
Okay, I can't figure it out.
I have an element inside the Draggable with onClick event. Actually I want to open modal window when click on the draggable element. And my onClick event thinks that dragging is a click. I tried to setup the local state to false onStart, onStop and to true onDrag and check my modal if this state is false before toggle, but it works not how I expected. Here is how: http://take.ms/1XdNl
Any suggestions how to set up logic properly?
Also hoping to see a draggable element that can have a separate click event, if anyone has an example.
Hi, there is my solution and it works fine for me.
onClick(event) {
// your code
}
onDrop(event) {
// your code
}
onDrag() {
this.setState({dragging: true})
}
onStop(...args) {
const {dragging} = this.state
this.setState({dragging: false})
if (dragging) {
this.onDrop(...args)
} else {
this.onClick(...args)
}
}
render() {
return (
<Draggable
onDrag={this.onDrag} // assume it's bound to `this`
onStop={this.onStop} // assume it's bound to `this`
/>
)
}
@maxight That worked perfectly for me. Thank you!
Thank you!
The proposed solution doesn't work if you have descendants that either draggable or clickable, and you cancel the drag for non-draggable elements.
More: https://github.com/mzabriskie/react-draggable/issues/350#issuecomment-560941853
It would be nice if the API would expose onClick event that ignores a cancelled drag event.
import React from 'react'
import Draggable from 'react-draggable'
const styles = {
homeButtonWrapper: {
position: 'fixed',
bottom: 20,
right: 40,
height: 48,
width: 48,
background: '#ccc'
}
}
const bounds = {
bottom: 0,
right: 0
}
const getLocalPosition = () => {
const position = localStorage.getItem('homeButtonPosition')
const positionJSON = (position && JSON.parse(position)) || {}
return {
x: positionJSON.x || 0,
y: positionJSON.y || 0
}
}
const setLocalPosition = (data) => {
localStorage.setItem('homeButtonPosition', JSON.stringify(data))
}
const HomeButtonProvider = (props) => {
const { children, portalDomain } = props
const [position, setPosition] = React.useState(getLocalPosition())
const onStop = (e, data) => {
e.stopPropagation()
const { x: lastX, y: lastY } = getLocalPosition()
setPosition({
x: data.x,
y: data.y
})
setLocalPosition({
x: data.x,
y: data.y
})
// mock onClick event, use lastX compare with this X, and lastY compare with this Y, if them is equal, do click, other do drag
if (lastX === data.x && lastY === data.y) {
window.open('{{{portalDomain}}}', '_self')
}
}
return (
<>
<Draggable
bounds={bounds}
position={position}
onStop={onStop}
>
<div title="goHome" style={styles.homeButtonWrapper}></div>
</Draggable>
{children}
</>
)
}
export default HomeButtonProvider
+1 I have the same problem: click events are not detected together with Draggable. I even tried to wrap draggable element with external event handler like this:
<div onClick={ () => this.handleClick} }
<Draggable>
</Draggable>
</div>
Still it doesn't work :( Yes, it would be great to expose external API onClick for cancelled drag events, as @Izhaki proposed
None of the other solutions here worked for me, so I'm comparing the position at the beginning and at the end to determine if something is a click or not:
import Draggable from 'react-draggable';
function MyDraggableComponent(){
const [boundingBox, setBoundingBox] = useState({});
const handleStart = (e) => {
setBoundingBox(e.target.getBoundingClientRect());
}
const handleStop = (e) => {
const { top, left } = e.target.getBoundingClientRect();
// compare the start position to the current one
// if no change, assume this is a simple click
if(top === boundingBox.top && left === boundingBox.left){
handleClick(e);
}
}
const handleClick = (e) => {
console.log('click!');
}
// don't forget to remove the onClick event from the child -- we're simulating that in the handleStop
return (
<Draggable
onStart={handleStart}
onStop={handleStop}
>
<div>Draggable stuff</div>
</Draggable>
)
}
export default MyDraggableComponent;```
For me the following worked:
<Draggable>
<button
onMouseDown((evt) => {
evt.stopPropagation();
onClose();
})
>
Close
</button>
</Draggable>
Hey, I'm facing a similar problem with OnClick & OnDrag.
Currently, I have to click, and then the draggable piece will follow my mouse. I think it'd be a bit more intuitive if all I had to do was hold down click and drag, then release to drop the draggable piece to the dragged location. (Demo : the road pieces in https://detour-bus-site.web.app/)
How can I fix this? Drag seems to work fine on mobile devices, but creates this issue on desktop for me.
Here is how I did it
<Draggable
handle=".dragHandle"
position={{ x: positionX, y: positionY }}
onStart={(_e: DraggableEvent, data: DraggableData) => {
setLastPositionX(data.x);
setLastPositionY(data.y);
}}
onStop={(e: DraggableEvent, data: DraggableData) => {
e.stopPropagation();
if (data.x === lastPositionX && data.y === lastPositionY) {
// drag did not change anything. Consider this to be a click
openCallingConversation();
}
setPositionX(data.x);
setPositionY(data.y);
}}
>
I experienced this issue where buttons inside a drag handle element could not be clicked on touch devices only. The buttons worked on mouse devices but didn't receive clicks on iOS devices or in Chrome's touch device simulator.
Because I have multiple buttons inside the draggable element I couldn't use the solutions above directly, though they did inspire my work-around.
I ended up forcibly triggering a click on the drag event's target element inside onStop like this (with Typescript hackery):
(event?.target as HTMLButtonElement)?.click?.();
You could probably also run this instead inside a try / catch:
event.target.click();
Here's my approach in more detail, including distinguishing real drags from clicks:
const dragStartPositionXYRef = useRef<{ x: number; y: number }>();
<Draggable
// Other stuff...
onStart={(event) => {
// Record the starting position of the drag, so we can detect later if
// the user actually dragged the popup or just clicked on it
dragStartPositionXYRef.current = { x: data.x, y: data.y };
}
onDragStop={(event, data) => {
// Only treat the drag as a real one if the popup moved at least a
// threshold number of pixels in any direction
const THRESHOLD = 2;
const { x, y } = dragStartPositionXYRef.current ?? { x: 0, y: 0 };
const wasDragged = Math.abs(data.x - x) > THRESHOLD && Math.abs(data.y - y) > THRESHOLD;
if (!wasDragged) {
(event?.target as HTMLButtonElement)?.click?.();
}
}
/>