forked from use-platform/use-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseFocusable.ts
More file actions
31 lines (25 loc) · 727 Bytes
/
useFocusable.ts
File metadata and controls
31 lines (25 loc) · 727 Bytes
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
import { HTMLAttributes, RefObject, useEffect } from 'react'
import { focusElement } from '../../libs/dom-utils'
import type { FocusableDOMProps } from '../../shared/types'
export interface UseFocusableProps extends FocusableDOMProps {
disabled?: boolean
}
export interface UseFocusableResult<T> {
focusableProps: HTMLAttributes<T>
}
export function useFocusable<T extends HTMLElement = HTMLElement>(
props: UseFocusableProps,
ref: RefObject<T>,
): UseFocusableResult<T> {
const { autoFocus, disabled, tabIndex } = props
useEffect(() => {
if (autoFocus) {
focusElement(ref.current)
}
}, [autoFocus, ref])
return {
focusableProps: {
tabIndex: disabled ? -1 : tabIndex,
},
}
}