I've been working with React and TypeScript, and I recently added the W3School drag div example to my React app. However, I'm facing an issue where the draggable div is moving outside of the container. Can someone please guide me on how to confine the draggable div within the boundary without relying on any third-party libraries?
Here is a link to my sandbox demo
Here's my code:
import "./styles.css";
import React, { useRef } from "react";
export default function App() {
const dragRef = useRef<HTMLDivElement>(null);
let pos1 = 0,
pos2 = 0,
pos3 = 0,
pos4 = 0;
const drag = (event: any) => {
const boundingBox = dragRef.current;
if (boundingBox) {
event = event || window.event;
event.preventDefault();
pos1 = pos3 - event.clientX;
pos2 = pos4 - event.clientY;
pos3 = event.clientX;
pos4 = event.clientY;
boundingBox.style.top = boundingBox.offsetTop - pos2 + "px";
boundingBox.style.left = boundingBox.offsetLeft - pos1 + "px";
}
};
const stop = () => {
const boundingBox = dragRef.current;
if (boundingBox) {
boundingBox.onmouseup = null;
boundingBox.onmousemove = null;
}
};
const start = (event: any) => {
const box = dragRef.current;
if (box) {
event = event || window.event;
event.preventDefault();
pos3 = event.clientX;
pos4 = event.clientY;
box.onmouseup = stop;
box.onmousemove = drag;
}
};
return (
<div className="App">
<div
ref={dragRef}
className="draggableDiv"
onMouseDown={start}
onMouseMove={drag}
onMouseUp={stop}
></div>
</div>
);
}
And here's the external CSS file:
.App {
font-family: sans-serif;
height: 350px;
width: 400px;
background-color: rgb(132, 190, 241);
position: relative;
}
.draggableDiv {
position: absolute;
height: 40px;
width: 40px;
background-color: red;
cursor: grab;
}