Skip to content

Latest commit

Β 

History

History
36 lines (26 loc) Β· 935 Bytes

useMouse.md

File metadata and controls

36 lines (26 loc) Β· 935 Bytes

useMouse and useMouseHovered

React sensor hooks that re-render on mouse position changes. useMouse simply tracks mouse position; useMouseHovered allows you to specify extra options:

  • bound β€” to bind mouse coordinates withing the element.
  • whenHovered β€” whether to attach mousemove event handler only when user hovers over the element.

Usage

import {useMouse} from 'react-use';

const Demo = () => {
  const ref = React.useRef(null);
  const {docX, docY, posX, posY, elX, elY, elW, elH} = useMouse(ref);

  return (
    <div ref={element}>
      <div>Mouse position in document - x:{docX} y:{docY}</div>
      <div>Mouse position in element - x:{posX} y:{posY}</div>
      <div>Element position - x:{elX} y:{elY}</div>
      <div>Element dimensions - {elW}x{elH}</div>
    </div>
  );
};

Reference

useMouse(ref);
useMouseHovered(ref, {bound: false, whenHovered: false});