Skip to content

Commit

Permalink
feat: add useHover sensor
Browse files Browse the repository at this point in the history
  • Loading branch information
kripod committed Oct 25, 2019
1 parent 026f04c commit 888a5cb
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/web-api-hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export { default as useDocumentVisibility } from './useDocumentVisibility';
export { default as useEventListener } from './useEventListener';
export { default as useFocus } from './useFocus';
export { default as useGeolocation } from './useGeolocation';
export { default as useHover } from './useHover';
export { default as useInterval } from './useInterval';
export { default as useLocalStorage } from './useLocalStorage';
export { default as useMedia } from './useMedia';
Expand Down
47 changes: 47 additions & 0 deletions packages/web-api-hooks/src/useHover.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useState } from 'react';

/**
* Tracks hover state of an element.
*
* @param disallowTouch Determines whether touch gestures should be ignored.
* @returns Whether the element is hovered, and props to be spread over the element under observation.
*
* @example
* function Component() {
* const [isHovered, bindHover] = useHover();
* // ...
* return <ElementToObserve {...bindHover} />;
* }
*/
export default function useHover(
disallowTouch = false,
): [
boolean,
Readonly<{
onMouseEnter: () => void;
onMouseLeave: () => void;
onTouchStart: () => void;
onTouchEnd: () => void;
}>,
] {
const [isHovered, setHovered] = useState(false);

return [
isHovered,
{
onMouseEnter() {
setHovered(true);
},
onMouseLeave() {
setHovered(false);
},

onTouchStart() {
setHovered(!disallowTouch);
},
onTouchEnd() {
setHovered(false);
},
},
];
}

0 comments on commit 888a5cb

Please sign in to comment.