Created
August 4, 2023 16:06
-
-
Save moritzsalla/2f1fea6c77889461265c34e45aebe6e6 to your computer and use it in GitHub Desktop.
This file contains 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
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