-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcheckbox.tsx
More file actions
70 lines (65 loc) · 2.25 KB
/
checkbox.tsx
File metadata and controls
70 lines (65 loc) · 2.25 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'use client'
import * as React from 'react'
import { cn } from '@/lib/utils'
import { CheckIcon } from 'lucide-react'
export interface CheckboxProps extends Omit<
React.InputHTMLAttributes<HTMLInputElement>,
'type'
> {
onCheckedChange?: (checked: boolean) => void
}
export const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
(
{
className,
checked,
defaultChecked,
onCheckedChange,
onChange,
...props
},
ref
) => {
const [isChecked, setIsChecked] = React.useState(
defaultChecked ?? false
)
const controlledChecked = checked ?? isChecked
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newChecked = e.target.checked
if (checked === undefined) {
setIsChecked(newChecked)
}
onCheckedChange?.(newChecked)
onChange?.(e)
}
return (
<label className="relative inline-flex cursor-pointer items-center">
<input
type="checkbox"
className="peer sr-only"
checked={controlledChecked}
onChange={handleChange}
ref={ref}
{...props}
/>
<div
className={cn(
'flex size-4 shrink-0 items-center justify-center rounded-sm border border-primary ring-offset-background transition-colors',
'peer-checked:bg-primary peer-checked:text-primary-foreground',
'peer-focus-visible:ring-2 peer-focus-visible:ring-ring peer-focus-visible:ring-offset-2',
'peer-disabled:cursor-not-allowed peer-disabled:opacity-50',
className
)}
>
<CheckIcon
className={cn(
'size-3.5 opacity-0 transition-opacity',
controlledChecked && 'opacity-100'
)}
/>
</div>
</label>
)
}
)
Checkbox.displayName = 'Checkbox'