ui: Default value not showing the correct selected value
I have a button with action to set a sorting on select input. On that button i change the value on useState from latest -> price-low-high.
When the button clicked the value inside render-value class changed. but the default value for the select not changed.
const [sort, setSort] = useState<string>('latest')
<div className="flex items-center w-full md:w-auto">
<div className="render-value">{sort}</div>
<button onClick={()=> setSort('price-low-high')}>CHANGE SORT VALUE<button>
<Label htmlFor="sorting" className="mr-2 text-gray-500 hidden md:block">Sorting {sort}</Label>
<Select onValueChange={value=> selectSort(value)}
defaultValue={sort}>
<SelectTrigger className="w-full md:w-[200px]">
<SelectValue placeholder="Select Sorting" />
</SelectTrigger>
<SelectContent id="sorting">
<SelectItem value="latest">Latest Product {sort}</SelectItem>
<SelectItem value={'price-low-high'}>Price: Low - High</SelectItem>
<SelectItem value={'price-high-low'}>Price: High - Low</SelectItem>
</SelectContent>
</Select>
</div>
About this issue
- Original URL
- State: open
- Created 10 months ago
- Reactions: 13
- Comments: 16
@yousihy @codingwithashu I hope you are aware of the fact that
defaultValueshould be used only when you do not need to control the state of the select. You might need to usevalueinstead. See ThisFor my case, the issue was that I needed to strictly specify that the value is a
stringalthough the type was astring. This applies to ALLshadcncontrols by the way.So, I had to convert the
stringto astringvalue={data.id.toString()}So, the
SelectContentwould look like this:solved π― π π π₯
Actually, due to the fact that shadcn uses radix in itself and when you are importing the select component, it is probably wrongly imported from radix and you just need to import it from the select component related to shadcn. This was the problem with my code and I realized it after a few days
import { SelectItem, SelectValue } from β@radix-ui/react-selectβ; //wrong import
import {SelectItem, SelectValue } from β@/components/ui/selectβ; //correct import
This did not work for me or it didnβt have any effect on my problem. My controls are working fine with
valueonly. My issue was that I needed to ensure that I am passing astringto thevalueproperty of theSelectItemeven though the type of that value is actually a string. See my comment aboveI was also having trouble getting this to work. But @hardikchopra242 nailed it for me. The example of usage in a form in the docs leads to this mistake (defaultValue instead of value).
@yousihy Thanks!
this saved me to waste much more time on this
@yousihy , have you resolved this?
This fixed my issue.
As the Radix docs state:
If you need more flexibility, you can control the component using value/onValueChange props and passing children to SelectValue.It works π
For set the defaulValues for the form use: