Solving Div resizing errors in React
P粉204079743
P粉204079743 2024-03-28 18:15:06
0
1
451

I'm learning ReactJS, and I started a small project to learn it. I'm trying to create a div that can be resized by dragging. This is my code:

import { useRef, useState } from 'react';
import PostViewer from '../PostViewer/PostViewer';
import './ContainerResize.scss'
import * as htmlToImage from 'html-to-image';
import { toPng } from 'html-to-image';
import download from 'downloadjs'


function savePng() {
    htmlToImage.toPng(document.getElementById('Resizable'))
        .then(function (dataUrl) {
            download(dataUrl, 'tweet.png');
        });
}

const ContainerResize = (props) => {

    const [initialPos, setInitialPos] = useState(null);
    const [initialSize, setInitialSize] = useState(null);
    const resizable = useRef(null);

    const initial = (e) => {
        setInitialPos(e.clientX);
        setInitialSize(resizable.current.offsetWidth);
        console.log(resizable.current.offsetWidth)
    }

    const resizeLeft = (e) => {
        resizable.current.style.width = `${parseInt(initialSize) + parseInt(initialPos - e.clientX)}px`;
    }

    const resizeRight = (e) => {
        resizable.current.style.width = `${parseInt(initialSize) + parseInt(e.clientX - initialPos)}px`;
    }

    return (
        <div className="containerResize">
            <button onClick={savePng}>Save</button>
            <div
                id="Draggable"
                draggable="true"
                onDragStart={initial}
                onDrag={resizeLeft}
            />
            <div id="Resizable" ref={resizable}>
                <PostViewer tweetParam={props.tweetParam} />
            </div>
            <div
                id="Draggable"
                draggable="true"
                onDragStart={initial}
                onDrag={resizeRight}
            />
        </div>
    );
}

export default ContainerResize;

Resize on the right works fine, but resize on the left does not. In fact, when I drag with the left side, the div resizes correctly, but when I drop the button, the div retakes its initial position.

Have you solved my problem?

Thank you very much for your reply:)

P粉204079743
P粉204079743

reply all(1)
P粉006847750

This is a super annoying error. The problem is that when the mouse is released during onDrag, the event is fired and event.clientX is set to 0.

A quick fix to this problem is to check if event.clientX === 0 and return it from the function.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template