Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Drag functionality only working from right to left, but not from left to right

Below is the code(not very elegant or complete, but working) for the dragging functionality in react version 17. Dragging the element works from left to right, but not from right to left. Can anyone please advise the issue or is something is missing.


    import React, { useState, useEffect } from "react";
    const Draggables = (props) => {
      const [dragging, setDragging] = useState(false);
      const [pos, setPos] = useState({ x: 0, y: 0 });
    
      useEffect(() => {
        if (dragging) {
          document.addEventListener("mousemove", { onMouseMove });
          document.addEventListener("mouseup", { onMouseUp });
        } else if (!dragging) {
          document.removeEventListener("mousemove", { onMouseMove });
          document.removeEventListener("mouseup", { onMouseUp });
        }
      }, [dragging]);
    
      const mouseDown = (e) => {
        // only left mouse button
        if (e.button !== 0) return;
         setDragging(true);
        e.stopPropagation();
        e.preventDefault();
      };
    
      const onMouseUp = (e) => {
        setDragging(false);
        e.stopPropagation();
        e.preventDefault();
      };
    
      const onMouseMove = (e) => {
        if (!dragging) return;
        setPos({
          x: e.pageX,
        });
        e.stopPropagation();
        e.preventDefault();
      };
    
      return (
        <div className="draggable"
          onMouseDown={mouseDown}
          onMouseMove={onMouseMove}
          onMouseUp={onMouseUp}
    
          style={{
            position: "absolute",
            left: `${pos.x}px`,
            top: 50 + "px",
          }}
        >
          D
        </div>
      );
    };
    
    export default Draggables;

Below is the corresponding CSS.


    .draggable {
      cursor: pointer;
      width: 4px;
      height: 4px;
      border-radius: 50px;
      background-color: blue;
    }

Thanks

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!