Created
May 19, 2022 05:00
-
-
Save goooooouwa/e93892c5f90f27bd850da27c6238f30a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import interact from "interactjs"; | |
import React, { useEffect, useState } from "react"; | |
export default function Draggable() { | |
const [positionX, setPositionX] = useState(0); | |
// This issue has to do with the following combination: | |
// - add interactjs event listeners inside useEffect | |
// - set react useEffect dependency list as [] | |
// - call react setState method inside event listeners | |
// Result: | |
// interactjs actions not working properly | |
useEffect(() => { | |
interact('.draggable').draggable({ | |
listeners: { | |
start(event) { | |
console.log(event.type, event.target) | |
}, | |
move(event) { | |
let positionx = positionX + event.dx | |
event.target.style.transform = | |
`translate(${positionx}px)` | |
setPositionX(positionx) | |
}, | |
} | |
}) | |
},[]); | |
return ( | |
<> | |
<div className="draggable">Drag me</div> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment