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 user click on the top-left resize handler, isDragging is set to true
then handleMouseMove will resize an move the div 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 resize slightly from the right border arccording to default resizing behavior when it should be resizing from the left because setPosition is not running.
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 expand from the right border 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!