Skip to content

Commit

Permalink
fix: account for mousemove
Browse files Browse the repository at this point in the history
  • Loading branch information
therealparmesh committed Jan 19, 2020
1 parent 97631e8 commit f47a903
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
31 changes: 31 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,21 @@
import React from 'react';

export const useHovering = () => {
const ref = React.useRef();
const [hovering, setHovering] = React.useState(false);

const bind = React.useMemo(
() => ({
ref,
onMouseEnter: () => {
setHovering(true);
},
onMouseLeave: () => {
setHovering(false);
},
onMouseMove: () => {
setHovering(true);
},
onFocus: () => {
setHovering(true);
},
Expand All @@ -22,5 +27,31 @@ export const useHovering = () => {
[],
);

React.useEffect(() => {
const listener = e => {
const minX = ref.current.offsetLeft;
const maxX = minX + ref.current.offsetWidth;
const minY = ref.current.offsetTop;
const maxY = minY + ref.current.offsetHeight;

if (
!(
e.clientX >= minX &&
e.clientX <= maxX &&
e.clientY >= minY &&
e.clientY <= maxY
)
) {
setHovering(false);
}
};

document.addEventListener('mousemove', listener);

return () => {
document.removeEventListener('mousemove', listener);
};
}, []);

return [hovering, bind];
};
2 changes: 2 additions & 0 deletions types.d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
declare function useHovering(): [
boolean,
{
ref: React.RefObject<any>;
onMouseEnter: React.MouseEventHandler<any>;
onMouseLeave: React.MouseEventHandler<any>;
onMouseMove: React.MouseEventHandler<any>;
onFocus: React.FocusEventHandler<any>;
onBlur: React.FocusEventHandler<any>;
tabIndex: React.HTMLAttributes<any>['tabIndex'];
Expand Down

0 comments on commit f47a903

Please sign in to comment.