UNPKG

@ducor/form

Version:
35 lines (34 loc) 3.08 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { Controller, useFormContext } from "react-hook-form"; import { uuidv4 } from "./utils"; import { twMerge } from "tailwind-merge"; import Label from "./components/label"; import HelperText from "./components/helperText"; import Errors from "./components/errors"; export const Radio = ({ name, label, options, id, direction = "vertical", withAsterisk, helperText, defaultValue, disabled, className, }) => { const { control, formState: { errors }, } = useFormContext(); const controlId = id || uuidv4(); return (_jsxs("div", { className: twMerge("flex", direction === "horizontal" ? "flex-row items-center gap-4" : "flex-col gap-2"), children: [label && (_jsx(Label, { id: controlId, label: label, withAsterisk: withAsterisk })), _jsxs("div", { className: 'w-full', children: [_jsx(Controller, { name: name, control: control, rules: { required: withAsterisk ? "This field is required" : false, }, defaultValue: defaultValue, render: (_a) => { var _b = _a.field, { value, onChange } = _b, field = __rest(_b, ["value", "onChange"]); return (_jsx("div", { className: twMerge("grid gap-2", className), children: options.map((option) => { const optionId = `${controlId}-${option.value}`; const isChecked = value === option.value; return (_jsxs("label", { htmlFor: optionId, className: twMerge("flex items-center gap-2 cursor-pointer", disabled && "cursor-not-allowed opacity-50"), children: [_jsxs("div", { className: 'relative flex items-center', children: [_jsx("input", Object.assign({ type: 'radio', id: optionId, value: option.value, checked: isChecked, disabled: disabled, onChange: (e) => onChange(e.target.value) }, field, { className: twMerge("w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 ", errors[name] && "border-red-500 focus:ring-red-400") })), isChecked && (_jsx("div", { className: 'absolute inset-0 flex items-center justify-center pointer-events-none', children: _jsx("div", { className: 'w-2 h-2 bg-blue-600 rounded-full' }) }))] }), _jsx("span", { className: 'text-sm text-gray-700 dark:text-gray-200', children: option.label })] }, option.value)); }) })); } }), helperText && _jsx(HelperText, { helperText: helperText }), errors[name] && _jsx(Errors, { value: errors[name] })] })] })); };