forked from use-platform/use-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseCheckbox.ts
More file actions
33 lines (28 loc) · 859 Bytes
/
useCheckbox.ts
File metadata and controls
33 lines (28 loc) · 859 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
32
33
import { HTMLAttributes, InputHTMLAttributes, RefObject, useEffect } from 'react'
import { useToggle } from '../toggle'
import { CommonCheckboxProps } from './types'
export interface UseCheckboxResult {
isPressed: boolean
rootProps: HTMLAttributes<HTMLElement>
inputProps: InputHTMLAttributes<HTMLInputElement>
}
export function useCheckbox(
props: CommonCheckboxProps,
ref: RefObject<HTMLInputElement>,
): UseCheckboxResult {
const { indeterminate = false, ...restProps } = props
const toggle = useToggle(restProps, ref)
// Use effect for apply state after component render.
useEffect(() => {
if (ref.current) {
ref.current.indeterminate = indeterminate
}
})
return {
...toggle,
inputProps: {
...toggle.inputProps,
'aria-checked': indeterminate ? 'mixed' : toggle.inputProps.checked,
},
}
}