mantine-entity
Version:
A library combining Mantine, TanStack Query, and Mantine React Table for efficient entity management
44 lines (43 loc) • 2.37 kB
JavaScript
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { forwardRef } from "react";
import { Group, InputDescription, InputError, InputLabel, InputWrapper, Checkbox, Stack, } from "@mantine/core";
import { useController, } from "react-hook-form";
const CheckboxGroupInput = forwardRef(({ control, name, data, label, description, error, required = false, orientation = "vertical", inputWrapperOrder = ["label", "description", "input", "error"], withAsterisk, defaultValue, }, ref) => {
const { field: { value = [], onChange }, fieldState: { error: fieldError }, } = useController({
control,
name,
rules: required ? { required: "This field is required" } : {},
defaultValue: defaultValue || [],
});
const handleCheckboxChange = (optionValue, checked) => {
const currentValues = Array.isArray(value) ? value : [];
if (checked) {
onChange([...currentValues, optionValue]);
}
else {
onChange(currentValues.filter((v) => v !== optionValue));
}
};
const Container = orientation === "horizontal" ? Group : Stack;
const errorMessage = error || fieldError?.message;
const content = inputWrapperOrder.map((part) => {
switch (part) {
case "label":
return (_jsx(InputLabel, { required: withAsterisk, children: label }, "label"));
case "input":
return (_jsx(Checkbox.Group, { defaultValue: defaultValue, value: value, onChange: (v) => onChange && onChange(v), size: "xs", className: `mb-1 ${error && "border border-[var(--mantine-color-error)]"}`, children: _jsx(Container, { gap: "xs", children: data?.map((item) => (_jsx(Checkbox, { radius: "md", value: item.value }, item.value))) }) }, "input"));
case "description":
return (_jsx(InputDescription, { children: description }, "description"));
case "error":
return (_jsx(InputError, { ta: "left", children: errorMessage }, "error"));
default:
return null;
}
});
if (data && data.length >= 1) {
return (_jsxs(InputWrapper, { children: [_jsx("button", { ref: ref, style: { display: "none" } }), content] }));
}
return null;
});
CheckboxGroupInput.displayName = "CheckboxGroupInput";
export default CheckboxGroupInput;