javascriptcssreactjsaddeventlistenerreact-flow

How can I set the cursor to 'grabbing' when panning in react-flow?


I am using react-flow and the user can pan around by clicking and dragging on the background. I would like the cursor to be 'grab' when hovering over the background, and the cursor to be 'grabbing' while the user has the mouse button down and is dragging/panning around.

What is working:

I have been able to get the cursor to be 'grab' while hovering over the background by setting the style on ReactFlow like so:

<ReactFlow
      style={{ cursor: "grab" }}
      ...

What is not working:

I can't get the cursor to be 'grabbing' while the mouse button is held down over the background.

What I've tried:

I've tried setting the cursor conditionally based on a mouseDown state variable like this: style={{ cursor: mouseDown ? 'grabbing' : 'grab' }}

But for some reason the mouseDown/mouseUp events do not fire with the mouse over the background, even though they fire when clicking on other elements. Here's how I've tried to do that:

  const [mouseDown, setMouseDown] = useState(false);

  const handleMouseDown = () => {
    setMouseDown(true);
    console.log('mouse down');
  };

  const handleMouseUp = () => {
    setMouseDown(false);
    console.log('mouse up');
  };

  useEffect(() => {
    window.addEventListener('mousedown', handleMouseDown);
    window.addEventListener('mouseup', handleMouseUp);
    return () => {
      window.removeEventListener('mousedown', handleMouseDown);
      window.removeEventListener('mouseup', handleMouseUp);
    };
  }, []);

Here's a codesandbox example where the cursor is correctly set to 'grab', but does not get set to 'grabbing' (see the src/Flow.js file):

Edit hopeful-ellis-nr675y


Solution

  • instead add listener to window how bout using react flow's event api instead? your code work perfectly if u doing right click. maybe react flow's do stopPropagation() for left mouse

    <ReactFlow
      style={{ cursor: mouseDown ? "grabbing" : "grab" }}
      nodes={nodes}
      edges={edges}
      onNodesChange={onNodesChange}
      onEdgesChange={onEdgesChange}
      onConnect={onConnect}
      onInit={onInit}
      fitView
    
      onMoveStart={handleMouseDown} 
      onMoveEnd={handleMouseUp}
    >