I’m creating a chessboard where I’d like to being able to drag and drop the pieces between squares of the chessboard, as well as move them with point and click (click origin square once, click target square once). In order to do this I’m leveraging onMouseDown, onMouseUp, and onMouseMove. These each have handler functions attached to them. onMouseDown and onMouseUp are attached to the individual square components of the chessboard so that I can get information about which square I’m clicking when I use them. onMouseMove on the other hand is attached to the chessboard itself.
handleMouseDown toggles a state variable that tracks whether we’re dragging or not to true. It then takes a copy of the piece element on the clicked square and moves it into a state variable used by the chessboard (dragPiece) which tracks which piece we’re supposed to be dragging around.
function handleMouseDown(e: React.MouseEvent, squareClicked: number) {
if (e.button !== 0) return; //If not a left mouse click
if (!pieces[squareClicked]) return;
setIsDragging(true);
setSelectedOrigin(squareClicked);
setDragPiece(testDragPiece); //Will have to change this to dynamic drag piece later
const piecesCopy = pieces.slice();
piecesCopy[squareClicked] = null;
setPieces(piecesCopy);
handleMouseMove only moves the dragged piece:
function handleMouseMove(e: React.MouseEvent) {
if (!isDragging) return;
//TODO: Return center of this thing dynamically based on board size
const containerRect = e.currentTarget.getBoundingClientRect();
const mouseX = e.clientX - containerRect.left - 60;
const mouseY = e.clientY - containerRect.top - 60;
setPosition({x: mouseX, y: mouseY});
}
Now, we come to the problem. When I call setPosition, my onMouseUp event never fires. If I remove this line from the code (meaning I stop dragging the piece around) onMouseUp fires just fine.
I think this may have something to do with setPosition triggering rerenders but I’m not sure – even if I stop moving and let the mouse go onMouseUp doesn’t fire. I’ve considered using useRef to track the position of the piece instead and then setPosition using useRef but I think that will simply end up in the same issue.
Please let me know if you need more info and thank you very much.