Reputation: 31
I am learning ReactJS and I started a small project to learn it. I try to create a div which is able to be resized by dragging it. 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;
The resize on right works fine but the resize on left doesn't work. Indeed, when i drag with the left side, the div is resized correctly but when I drop the button, the div retake its initial position.
Have you got a solution to my issue please ?
Thanks a lot for your responses :)
Upvotes: 0
Views: 399
Reputation: 617
This was a super annoying bug. the issue is that when the mouse is released during onDrag the event is fired with event.clientX
being set to 0.
a quick fix to this would be to check if event.clientX === 0
and return out of the function.
Upvotes: 1