rebuff
rebuff

Reputation: 33

React Hooks: how to resize a single div?

So I have this problem that I cannot resize a single div because my mouseup is not working...

    const [ isResizable, setIsResizable ] = useState(false);
    const [ newWidth, setIsNewWidth ] = useState(width);

    function handleResize() {
        setIsResizable(true);
    }


    function handleMouseMove(event) {
        if(isResizable) {
            let offsetRight =
            document.body.offsetWidth - (event.clientX - document.body.offsetLeft);
            let minWidth = 50;
            let maxWidth = 700;
            if(offsetRight > minWidth && offsetRight < maxWidth) {
                setIsNewWidth(offsetRight);
                console.log(width);
            }
        }
    }

    function handleMouseUp() {
        setIsResizable(false);
    }

    useEffect(() => {
        document.addEventListener('mousemove', e => handleMouseMove(e));
        document.addEventListener('mouseup', () => handleMouseUp());
    });

    return (
        <div
            className={`relative-drawer`}
            style={{
                width: newWidth,
                minWidth: 50
            }}>
            <div className={"dragable"} onMouseDown={() => handleResize()}></div>
        </div>
    );

Does anyone have an answer for this problem? I have tried alot but everything triggers as expected except the mousemove won't stop when handleMouseUp is called.

Upvotes: 1

Views: 1307

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 282120

The problem you have because you run the useEffect without any dependency which causes the subscription to be created again and again and thus causing issues as the mouseMove handler sets a state. You only need to add the subscription once on initial render and when isResizable variable changes

useEffect(() => {
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    return () => {
       document.removeEventListener('mousemove', handleMouseMove);
       document.removeEventListener('mouseup', handleMouseUp); 
    }
}, [isResizable]);

Working demo

P.S. You need to update your calculations for width

Upvotes: 3

Related Questions