Skip to content

Commit

Permalink
chore(Checkbox): added indeterminate state (#93)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjitrosch committed Apr 15, 2022
1 parent b08c004 commit 6added7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
7 changes: 6 additions & 1 deletion src/Checkbox/Checkbox.stories.tsx
Expand Up @@ -9,13 +9,18 @@ export default {
component: Checkbox,
} as Meta

export const Template: Story<CheckboxProps> = (args) => {
const Template: Story<CheckboxProps> = (args) => {
return <Checkbox {...args} />
}

export const Default = Template.bind({})
Default.args = {}

export const Indeterminate = Template.bind({})
Indeterminate.args = {
indeterminate: true
}

const FormTemplate: Story<CheckboxProps> = (args) => {
return (
<Form className="shadow bg-base-200 w-64 rounded-lg p-4">
Expand Down
26 changes: 24 additions & 2 deletions src/Checkbox/Checkbox.tsx
@@ -1,4 +1,9 @@
import React, { forwardRef } from 'react'
import React, {
forwardRef,
useEffect,
useImperativeHandle,
useRef
} from 'react'
import clsx from 'clsx'
import { twMerge } from 'tailwind-merge'

Expand All @@ -15,6 +20,7 @@ export type CheckboxProps = Omit<
IComponentBaseProps & {
color?: ComponentBrandColors
size?: ComponentSize
indeterminate?: boolean
}

const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
Expand All @@ -24,6 +30,7 @@ const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
defaultChecked = false,
color,
size,
indeterminate,
dataTheme,
className,
...props
Expand All @@ -39,10 +46,25 @@ const Checkbox = forwardRef<HTMLInputElement, CheckboxProps>(
})
)

const checkboxRef = useRef<HTMLInputElement>(null)
useImperativeHandle(ref, () => checkboxRef.current as HTMLInputElement)

useEffect(() => {
if (!checkboxRef.current) {
return
}

if (indeterminate) {
checkboxRef.current.indeterminate = true
} else {
checkboxRef.current.indeterminate = false
}
}, [indeterminate])

return (
<input
{...props}
ref={ref}
ref={checkboxRef}
type="checkbox"
checked={checked}
defaultChecked={defaultChecked}
Expand Down

0 comments on commit 6added7

Please sign in to comment.