I am having an issue with Shadcn
react library’s Select
component. It seems that "dynamically" generated SelectItem
is causing an issue were they are not displayed in the SelectValue
box when selected.
I am using Zod validation library. I am supposed to select from available types of properties. The selection works and Zod is getting the value. But the item is not being displayed in the select box. It is just showing empty
<FormField
control={form.control}
name="type"
render={({ field }) => (
<FormItem className="grid grid-cols-4 items-center gap-4">
<FormLabel className="sm:block sm:text-right">
Type
</FormLabel>
<Select
disabled={isSubmitting}
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger className="col-span-4 sm:col-span-3">
<SelectValue placeholder="Select a property type"/>
</SelectTrigger>
</FormControl>
<SelectContent className="SelectContent">
{propTypes.map((type) => (
<SelectItem key={type.id} value={type.id}>
{type.name}
</SelectItem>
))}
</SelectContent>
</Select>
</FormItem>
)}
/>
I am not seeing the value selected:
However, Zod is getting the value successfully:
Now, if I replace the dynamically generated values with static values as below, it will work, and I will be able to see what I selected:
<SelectContent>
<SelectItem value="[email protected]">[email protected]</SelectItem>
<SelectItem value="[email protected]">[email protected]</SelectItem>
<SelectItem value="[email protected]">[email protected]</SelectItem>
</SelectContent>
Something is wrong when we generate the SelectItem
dynamically.
Here is a codesandbox view:
https://codesandbox.io/p/sandbox/elastic-andras-35r33x
Any idea what is wrong here or how to fix it?
Thank you all.
2
Answers
In case anyone else had the same problem. There is something that many are missing. The
SelectItem
value
must be instring
value. Don't assume that you will get this converted for you.It should be like this:
I hope this will help anyone who found the same issue
I have struggled with the same problem. And solution for me was to retrive proer element from options array and assign it to default value. Analogously in your case it would look like this:
Possible you should adjust a liitlebit this code to your field properties. I hope I have helped!