Skip to content

Commit

Permalink
feat: add useFocus sensor
Browse files Browse the repository at this point in the history
  • Loading branch information
kripod committed Oct 25, 2019
1 parent b5884d8 commit 026f04c
Show file tree
Hide file tree
Showing 2 changed files with 36 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 @@ -5,6 +5,7 @@ export { default as useDeviceOrientation } from './useDeviceOrientation';
export { default as useDocumentReadiness } from './useDocumentReadiness';
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 useInterval } from './useInterval';
export { default as useLocalStorage } from './useLocalStorage';
Expand Down
35 changes: 35 additions & 0 deletions packages/web-api-hooks/src/useFocus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useState } from 'react';

/**
* Tracks focus state of an element.
*
* @returns Whether the element has focus, and props to be spread over the element under observation.
*
* @example
* function Component() {
* const [hasFocus, bindFocus] = useFocus();
* // ...
* return <ElementToObserve {...bindFocus} />;
* }
*/
export default function useFocus(): [
boolean,
Readonly<{
onFocus: () => void;
onBlur: () => void;
}>,
] {
const [isFocused, setFocused] = useState(false);

return [
isFocused,
{
onFocus() {
setFocused(true);
},
onBlur() {
setFocused(false);
},
},
];
}

0 comments on commit 026f04c

Please sign in to comment.