I am implementing myself Resizable without using libraries. Below is my handleMouseMove function:
useEffect(() => {
const handleMouseMove = (event : React.MouseEvent<HTMLDivElement> ) : void => {
if (isDragging) {
const deltaX: number = startCo.x - event.clientX;
const deltaY: number = startCo.y - event.clientY;
const newWidth: number = Math.max(10,dimension.width + deltaX);
const newHeight: number = Math.max(10, dimension.height + deltaY);
setDimension({ width: newWidth, height: newHeight });
if (newWidth > 10) {
const newPosX: number = position.x - deltaX;
const newPosY: number = position.y - deltaY;
setPosition({x: newPosX, y: newPosY});
}
setStartCo({ x: event.clientX, y: event.clientY });
console.log(deltaX)
}
...
When using click on the top-left resize handler, isDragging is set to true
then handleMouseMove will resize an move the iv accordingly.
The problem is, I want the lower limit of the div to be 10px x 10px, say when I resize the width from 11px to 10px, the dimension are updated but the position is not update because the width is now 10px. This cause the div to move slightly to the left when it should be stationary.
I tried replace
if (newWidth > 10)
with
if (dimension.width > 10)
because I think that width is updated later so the setPosition will run but this only make the div move slightly to the right when I resize from 10px to 11px.
I don’t know what to do, should I try another approach an re-buil from scratch?
Thank you!