import React, { createContext, forwardRef, useContext, useState } from "react"; import { cl } from "../../utils/helpers"; import { Fieldset, FieldsetProps } from "../fieldset"; import { FieldsetContext } from "../fieldset/context"; export interface CheckboxGroupState { readonly defaultValue?: readonly any[]; readonly value?: readonly any[]; toggleValue(value: any): void; } export const CheckboxGroupContext = createContext( null, ); export interface CheckboxGroupProps extends Omit< FieldsetProps, "onChange" | "errorPropagation" | "defaultValue" | "nativeReadOnly" > { /** * Collection of ``. */ children: React.ReactNode; /** * Controlled state for checkboxes. */ value?: any[]; /** * Default checked checkboxes. */ defaultValue?: any[]; /** * Returns current checked checkboxes in group. */ onChange?: (value: any[]) => void; } /** * A component that allows users to select one or more options from a list. * * @see [📝 Documentation](https://aksel.nav.no/komponenter/core/checkbox) * @see 🏷️ {@link CheckboxProps} * * @example * ```jsx * * Bil * Drosje * Kollektivt * * ``` */ export const CheckboxGroup = forwardRef< HTMLFieldSetElement, CheckboxGroupProps >( ( { value, defaultValue, onChange = () => {}, children, className, ...rest }, ref, ) => { const fieldset = useContext(FieldsetContext); const [state, setState] = useState(defaultValue ?? []); const toggleValue = (v: any) => { const newValue = value ?? state; const newState = newValue.includes(v) ? newValue.filter((x) => x !== v) : [...newValue, v]; value === undefined && setState(newState); onChange(newState); }; return (
{children}
); }, ); export default CheckboxGroup;