Files
web/packages/design-system/lib/components/Form/Checkbox/index.tsx
Anton Gunnarsson e5f8394f50 Merged in chore/move-checkbox-component (pull request #2501)
chore(SW-3145): Move checkbox component to design-system

* Inline type

* Remove error handling from Checkbox internals

* Move Form/Checkbox

* Fix self referencing imports


Approved-by: Joakim Jäderberg
2025-07-03 08:37:01 +00:00

85 lines
2.1 KiB
TypeScript

'use client'
import { forwardRef } from 'react'
import { Checkbox as AriaCheckbox } from 'react-aria-components'
import {
type RegisterOptions,
useController,
useFormContext,
} from 'react-hook-form'
import styles from './checkbox.module.css'
import { MaterialIcon } from '../../Icons/MaterialIcon'
import Caption from '../../Caption'
interface CheckboxProps extends React.InputHTMLAttributes<HTMLInputElement> {
name: string
registerOptions?: RegisterOptions
hideError?: boolean
topAlign?: boolean
errorCodeMessages?: Record<string, string>
}
const Checkbox = forwardRef<
HTMLInputElement,
React.PropsWithChildren<CheckboxProps>
>(function Checkbox(
{
className = '',
name,
children,
registerOptions,
hideError,
topAlign = false,
errorCodeMessages,
},
ref
) {
const { control } = useFormContext()
const { field, fieldState } = useController({
control,
name,
rules: registerOptions,
})
return (
<AriaCheckbox
className={`${styles.container} ${className}`}
isSelected={field.value}
onChange={field.onChange}
data-testid={name}
isDisabled={registerOptions?.disabled}
excludeFromTabOrder
>
{({ isSelected }) => (
<>
<span
className={`${styles.checkboxContainer} ${topAlign ? styles.topAlign : ''}`}
>
<span
className={styles.checkbox}
tabIndex={registerOptions?.disabled ? undefined : 0}
ref={ref}
>
{isSelected && (
<MaterialIcon icon="check" color="Icon/Inverted" />
)}
</span>
{children}
</span>
{fieldState.error && !hideError ? (
<Caption className={styles.error} fontOnly>
<MaterialIcon icon="info" color="Icon/Interactive/Accent" />
{(fieldState.error.message &&
errorCodeMessages?.[fieldState.error.message]) ||
fieldState.error.message}
</Caption>
) : null}
</>
)}
</AriaCheckbox>
)
})
export default Checkbox