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)

Most upvoted comments

Components Select, MenuItem from @mui/material don’t have such problem. I can easily use number type as value, no typescript compiler issues. It would be really great for shadcn be flexible too

I 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:

interface SelectFieldProps {
  items: SelectListItem[];
  field: {
    onChange: (value: string) => void;
    onBlur: () => void;
    value: object | undefined; // * define the value type here
    name: string;
    ref: Ref<any>;
  };
}

const SelectField = ({
  items,
  field,
}: SelectFieldProps) => {

  const handleFieldValue = (value: string) => {
    const parsedObject = JSON.parse(value); // *parse the object here

    console.log(parsedObject);
  };

  return (
    <Select onValueChange={handleFieldValue} disabled={disabled}>
      <SelectTrigger>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        <SelectGroup>
          <SelectLabel>{label}</SelectLabel>
              {items.map((item) => (
                <SelectItem
                  key={item.id}
                  value={JSON.stringify(item)} // *stringify the object here
                  textValue={item.name}
                  defaultValue="Select"
                >
                  {disabled ? disabledName : item.name}
                </SelectItem>
              ))}
        </SelectGroup>
      </SelectContent>
    </Select>
  );
};

export default SelectField;

define enum

const ThemeEnum = z.enum(["light", "dark", "system"])
type ThemeEnum = z.infer<typeof ThemeEnum>

schema

const formSchema = z.object({
  theme: ThemeEnum.optional(),
})

form field

        <FormField
          control={form.control}
          name="theme"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Theme</FormLabel>
              <Select
                onValueChange={(value) => field.onChange(ThemeEnum.parse(value))}
                defaultValue={field.value}>
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Select a theme" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  {ThemeEnum.options.map((theme) => (
                    <SelectItem key={theme} value={theme}>
                      {theme}
                    </SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </FormItem>
          )}
        />

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:

interface SelectProps<T> {
    children?: React.ReactNode;
    value?: T;
    defaultValue?: T;
    onValueChange?(value: T): void;
    open?: boolean;
    defaultOpen?: boolean;
    onOpenChange?(open: boolean): void;
    dir?: Direction;
    name?: string;
    autoComplete?: string;
    disabled?: boolean;
    required?: boolean;
}

Update SelectItemProps to:

interface SelectItemProps extends PrimitiveDivProps {
    value: T;
    disabled?: boolean;
    textValue?: string;
}

Finally npx patch-package @radix-ui/react-select

@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:

const formSchema = z.object({
  maxPlayers: z.preprocess((val) => {
    if (typeof val === "string") {
      return parseInt(val)
    }

    return val;
  }, z.number().min(1).max(5)),
})

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…

"react-hook-form": "^7.45.4",