Skip to content

Instantly share code, notes, and snippets.

@moritzsalla
Created August 4, 2023 16:06
Show Gist options
  • Save moritzsalla/2f1fea6c77889461265c34e45aebe6e6 to your computer and use it in GitHub Desktop.
Save moritzsalla/2f1fea6c77889461265c34e45aebe6e6 to your computer and use it in GitHub Desktop.
const FocusDemo = () => {
// with callback
const [inputRef, setInputFocus] = useFocus<HTMLInputElement>();
// on component mount
const ref = useAutoFocus<HTMLInputElement>();
return (
<>
<button onClick={setInputFocus} >
Focus
</button>
<input ref={inputRef} />
<input ref={autoFocusRef} />
</>
)
}
const useAutoFocus = <T extends HTMLElement>() => {
return useCallback((node: T) => {
if (node) {
node.focus();
}
}, []);
};
const useFocus = <T extends HTMLElement>() => {
const htmlElRef = useRef<T>(null)
const setFocus = () => {htmlElRef.current && htmlElRef.current.focus()}
return [ htmlElRef, setFocus ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment