0

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!

1 Answer 1

1

You can compute the new dimensions newWidth and newHeight and ensure they do not go below 10px like this:

let newWidth: number = dimension.width + deltaX;
let newHeight: number = dimension.height + deltaY;

if (newWidth < 10) newWidth = 10;
if (newHeight < 10) newHeight = 10;

Then you can update position only if the new size is above the minimum:

const newPosX: number = newWidth > 10 ? position.x - deltaX : position.x;
const newPosY: number = newHeight > 10 ? position.y - deltaY : position.y;

And finally update the states:

setDimension({ width: newWidth, height: newHeight });
setPosition({ x: newPosX, y: newPosY });
setStartCo({ x: event.clientX, y: event.clientY });
1
  • Hi! Thank you for your reply. Your solution does limit the dimension of the div but the resizing is still the same at the 11px to 10px mark. Commented Jun 22, 2024 at 11:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.