ui: Cannot use value other than string on Select's onValueChange
Form schema and hook?
const FormSchema = z.object({
theme: z.enum(['light', 'dark', 'system']),
});
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
theme: theme as z.infer<typeof FormSchema>['theme'],
},
});
Form:
<FormField
control={form.control}
name='theme'
render={({ field }) => (
<FormItem>
<FormLabel>Thema</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
Error:
Type '(event: "light" | "dark" | "system" | ChangeEvent<Element>) => void' is not assignable to type '(value: string) => void'.
Types of parameters 'event' and 'value' are incompatible.
Type 'string' is not assignable to type '"light" | "dark" | "system" | ChangeEvent<Element>'.ts(2322)
The onValueChange is typed as such:
export interface SelectProps {
...
onValueChange?(value: string): void;
How can I make this work with enum?
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 16
- Comments: 24 (1 by maintainers)
Components
Select,MenuItemfrom@mui/materialdon’t have such problem. I can easily usenumbertype as value, no typescript compiler issues. It would be really great for shadcn be flexible tooI think I found a solution for this, in my case I wanted to handle an object as a value, I stringified everything and then I parsed them.
example:
define enum
schema
form field
Just try this, it worked for me.
const itemSchema = z.object({ category_id: z.number({ required_error: “Category is required”, invalid_type_error: “Category must be a Id”, }), }); <Select onValueChange={(value) => field.onChange(Number(value)) } defaultValue={String(field.value)} value={String(field.value)} > </Select> )} />
This is the trick:
onValueChange={(value) => field.onChange(Number(value)) } defaultValue={String(field.value)} value={String(field.value)}Keep them as string and convert on the onValueChange function. Worked for me.Any update about this ?
Not sure why radix-ui make value a string type, but you can try patch-package the source code to support generic type: Find the source code in /node_modules/@radix-ui/ract-select/dist/index.d.mts
Update SelectProps to:
Update SelectItemProps to:
Finally
npx patch-package @radix-ui/react-selectThis is my solution. I hope it helps you.
https://medium.com/@lovebuizel/how-to-make-shadcn-ui-select-components-value-accept-empty-strings-and-other-types-93401e2f38bb
@shadcn I think this was closed by accident, we hadn’t found a solution for this.
ANNYONE found a solution, I cannot use other types than string
I found a simpler solution if you use Zod:
This way you can accept numbers and process the field if it was supplied as a string.
Why close this issue @niebag ? This is a really annoying inconvenience
Same issue here… So inconvenient…