@ducor/form
Version:
form package
28 lines (27 loc) • 2.36 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useFormContext, Controller } from "react-hook-form";
import { twMerge } from "tailwind-merge";
import { uuidv4 } from "./utils";
import Errors from "./components/errors";
import Label from "./components/label";
import HelperText from "./components/helperText";
export const Checkbox = ({ label, withAsterisk, direction = "vertical", name, helperText, id, className, disabled, options = [], }) => {
const { control, formState: { errors }, } = useFormContext();
const controlId = id || uuidv4();
return (_jsxs("div", { className: twMerge("flex flex-col gap-2", className), children: [label && (_jsx(Label, { id: controlId, label: label, withAsterisk: withAsterisk })), _jsx(Controller, { name: name, control: control, defaultValue: [], rules: {
required: withAsterisk ? "This field is required" : false,
}, render: ({ field: { value = [], onChange } }) => {
const handleCheckboxChange = (checkedValue) => {
const newValue = value.includes(checkedValue)
? value.filter((v) => v !== checkedValue)
: [...value, checkedValue];
onChange(newValue);
};
return (_jsx("div", { className: twMerge(direction === "horizontal"
? "flex flex-wrap gap-4"
: "flex flex-col gap-2"), children: options.map((option, index) => {
const optionId = `${id || name}-${index}`;
return (_jsxs("label", { htmlFor: optionId, className: 'flex items-center gap-2 cursor-pointer', children: [_jsx("input", { id: optionId, type: 'checkbox', value: option.value, checked: value.includes(option.value), onChange: () => handleCheckboxChange(option.value), disabled: disabled, className: twMerge("w-4 h-4 text-blue-600 bg-gray-100 dark:text-gray-200 border-gray-300 rounded ", disabled && "opacity-50 cursor-not-allowed", errors[name] && "border-red-500") }), label && _jsx("span", { children: option.label })] }, optionId));
}) }));
} }), helperText && _jsx(HelperText, { helperText: helperText }), errors[name] && _jsx(Errors, { value: errors[name] })] }));
};