SolidJSS
SolidJS3y ago
49 replies
jesseb34r

Confused by context updating in handleOnMouseDown()

I can share more code if needed but the component is pretty large and I don't think all the context is needed for this. I have a component for a drag and drop canvas that when clicked should set the starting mouse position and then calculates it's position based on the difference between the current mouse position and the starting mouse position. The problem is that the starting mouse position gets set multiple times even though I only want it set once. Does anyone know why this is happening?

const Draggable: VoidComponent<{ id: string }> = (props) => {
  const dragContext = useDragContext();

  const handleMouseUp = () => {
    document.removeEventListener("mousemove", dragContext.handleDrag);
    document.removeEventListener("mouseup", handleMouseUp);
  };

  const handleMouseDown: JSX.EventHandler<HTMLDivElement, MouseEvent> = (e) => {
    e.preventDefault();
    if (!dragContext.state.selectedElementIds.includes(props.id)) {
      dragContext.selectElement(props.id);
    } else {
      dragContext.unSelectElement(props.id);
    }

    dragContext.setDragStartMousePosition({ x: e.clientX, y: e.clientY });
    dragContext.setDragStartPositions();

    document.addEventListener("mousemove", dragContext.handleDrag);
    document.addEventListener("mouseup", handleMouseUp);
  };

  return (
    <div
      style={{
        top: `${dragContext.state.elements[props.id].position.y}px`,
        left: `${dragContext.state.elements[props.id].position.x}px`,
      }}
      classList={{
        "fixed h-40 w-40 rounded bg-blue3": true,
        "border-4 border-orange6":
          !!dragContext.state.selectedElementIds.includes(props.id),
      }}
      onMouseDown={handleMouseDown}
    />
  );
};
Was this page helpful?