blob: c7700e9695ea5c6c25a65112cd05c1fb65e4cd97 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import { RefObject, useEffect } from 'react';
export type UseInputAutofocusProps = {
/**
* The focus condition. True give focus to the input.
*/
condition: boolean;
/**
* An optional delay. Default: 0.
*/
delay?: number;
/**
* A reference to the input element.
*/
ref: RefObject<HTMLInputElement>;
};
/**
* Set focus on an input with an optional delay.
*/
const useInputAutofocus = ({
condition,
delay = 0,
ref,
}: UseInputAutofocusProps) => {
useEffect(() => {
const timer = setTimeout(() => {
if (ref.current && condition) {
ref.current.focus();
}
}, delay);
return () => {
clearTimeout(timer);
};
}, [condition, delay, ref]);
};
export default useInputAutofocus;
|