This repository was archived by the owner on Mar 24, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSelectField.tsx
More file actions
104 lines (97 loc) · 2.74 KB
/
SelectField.tsx
File metadata and controls
104 lines (97 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use client';
import { useFormContext } from 'react-hook-form';
import { FormItem, FormLabel, FormDescription } from '@/components/ui/form';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
import { memo } from 'react';
interface SelectFieldProps {
name: string;
label: string;
description?: string;
options: string[];
placeholder?: string;
disabled?: boolean;
required?: boolean;
className?: string;
}
// Using memo to prevent unnecessary re-renders
const SelectField = memo(function SelectField({
name,
label,
description,
options,
placeholder = 'Select an option',
disabled,
required = false,
className,
}: SelectFieldProps) {
const {
setValue,
watch,
formState: { errors },
} = useFormContext();
// Ensure value is always a string
const value = watch(name) || '';
// Check if this field has an error
const hasError = !!errors[name];
// Always use a clean error message for select fields rather than showing the enum error
const errorMessage = hasError ? 'Please select an option' : '';
return (
<FormItem className={className}>
<FormLabel
className={cn(
'font-medium text-base',
required &&
"after:content-['*'] after:ml-0.5 after:text-red-500 after:font-bold",
!required &&
"after:content-['(optional)'] after:ml-1.5 after:text-muted-foreground after:text-xs after:font-normal"
)}
>
{label}
</FormLabel>
{description && (
<FormDescription className="mt-2">{description}</FormDescription>
)}
{/* Hidden input to prevent autocomplete */}
<input type="hidden" autoComplete="off" />
<Select
onValueChange={(newValue) => {
setValue(name, newValue, {
shouldValidate: false, // Don't validate immediately on selection
shouldDirty: true,
shouldTouch: true,
});
}}
value={value}
disabled={disabled}
>
<SelectTrigger
className={cn(
'w-full',
hasError && 'border-red-500 focus:ring-red-500'
)}
>
<SelectValue placeholder={placeholder} className="" />
</SelectTrigger>
<SelectContent className="">
{options.map((option) => (
<SelectItem key={option} value={option} className="">
{option}
</SelectItem>
))}
</SelectContent>
</Select>
{/* Add direct error display that will always show */}
{hasError && (
<p className="text-sm font-medium text-red-400 mt-1">{errorMessage}</p>
)}
</FormItem>
);
});
export default SelectField;