Created
August 10, 2019 04:52
-
-
Save carpben/de968e377cbac0ffbdefe1ab56237573 to your computer and use it in GitHub Desktop.
useFocus.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const useFocus = () => { | |
const htmlElRef = useRef<HTMLElement>() | |
const setFocus = () => { | |
const currentEl = htmlElRef.current | |
currentEl && currentEl.focus() | |
} | |
return [setFocus, htmlElRef] as const | |
} |
Even better:
export default function useFocus<T extends HTMLElement = HTMLElement>() {
const ref = React.useRef<T>(null);
const setFocus = () => ref?.current?.focus?.();
return [ref, setFocus] as const;
}
and use like:
const [focusRef, setFocus] = useFocus<HTMLButtonElement>();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A bit better: