-
Notifications
You must be signed in to change notification settings - Fork 25
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: fix auto focus for inputs (#1040)
just don't look at the internals and you'll be good.
- Loading branch information
Showing
3 changed files
with
28 additions
and
9 deletions.
There are no files selected for viewing
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
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import type React from 'react'; | ||
|
||
import useEventCallback from './useEventCallback'; | ||
|
||
function useAutoFocusRef(autoFocus: boolean, bodyVisible: boolean): React.MutableRefObject<HTMLInputElement | null> { | ||
// eslint-disable-next-line no-undef | ||
const ref: React.MutableRefObject<HTMLInputElement | null> & { timeout?: NodeJS.Timeout } = useEventCallback( | ||
(element: HTMLInputElement | null) => { | ||
ref.current = element; | ||
if (autoFocus && bodyVisible && element) { | ||
if (ref.timeout) clearTimeout(ref.timeout); | ||
ref.timeout = setTimeout(() => { | ||
if (ref.timeout) delete ref.timeout; | ||
element.focus(); | ||
}, 0); | ||
} | ||
}, | ||
// eslint-disable-next-line no-undef | ||
) as unknown as React.MutableRefObject<HTMLInputElement> & { timeout?: NodeJS.Timeout }; | ||
return ref; | ||
} | ||
|
||
export default useAutoFocusRef; |