blob: d0fcd06afaff1a9c2da8887f5c91d7926ccddce9 (
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
 | 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.
 */
export 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]);
};
 |