Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.4 kB
3
Indexable
Never
import React, { useState, useRef } from 'react';
import { Box } from '@mui/material';

const DraggableText = () => {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [dragging, setDragging] = useState(false);
  const boxRef = useRef();

  const onMouseDown = (e) => {
    setDragging(true);
    const rect = boxRef.current.getBoundingClientRect();
    setPosition({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    });
    e.stopPropagation();
    e.preventDefault();
  };

  const onMouseUp = (e) => {
    setDragging(false);
    e.stopPropagation();
    e.preventDefault();
  };

  const onMouseMove = (e) => {
    if (!dragging) return;
    const rect = boxRef.current.getBoundingClientRect();
    setPosition({
      x: e.clientX - rect.left,
      y: e.clientY - rect.top,
    });
    e.stopPropagation();
    e.preventDefault();
  };

  return (
    <Box
      ref={boxRef}
      onMouseDown={onMouseDown}
      onMouseUp={onMouseUp}
      onMouseMove={onMouseMove}
      sx={{
        position: 'relative',
        width: '100px',
        height: '100px',
        backgroundColor: 'lightgrey',
        '&::after': {
          content: '"abc"',
          position: 'absolute',
          top: `${position.y}px`,
          left: `${position.x}px`,
        }
      }}
    />
  );
};

export default DraggableText;