In useDrag callback function, how to get access to the element which triggered the useDrag #562
-
I'm making a wysiwyg image editor using html components. When users add images, a border appears on the images. Also, resize handler appear on the sides like this: I've allotted the same ref to each resize corner, namely ...
const resizeRef = React.useRef<HTMLDivElement | null>(null);
useDrag((event, offset: [ox, oy]) => {
// Logic to change height/width of image element based on offset
...
const side = event.currentTarget.dataset // returns typ-error and doesn't exist
}, {ref: resizeRef});
return (
<div ref={resizeRef} data-side="top-left" className="styles...">
<div ref={resizeRef} data-side="top-right" className="styles...">
<div ref={resizeRef} data-side="bottom-left" className="styles...">
<div ref={resizeRef} data-side="bottom-right" className="styles...">
)
... In the (What I've considered)I know that one ref should only be used with one element, and I shouldn't assign the Any suggestions would be appreciated 😃 |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
The element that triggered useDrag is event.currentTarget. You should either do this: useDrag(({ arg: [side] }) => {
switch(side) {
case 'top-left':
case 'top-right':
...
}
})
<div {...bind('top-left')} />
<div {...bind('top-right')} /> or const Handle = ({ side }) => {
const ref = useRef()
useDrag(() => {
switch(side) {
case 'top-left':
case 'top-right':
...
}
}, { target: ref })
}
return <div ref={ref} />
}
const App = () => {
return <>
<Handle side="top-left" />
<Handle side="top-right" />
</>
} |
Beta Was this translation helpful? Give feedback.
The element that triggered useDrag is event.currentTarget.
You definitely shouldn't assign a ref to several elements, prototyping or not prototyping.
You should either do this:
or