I'm using React with Shadcn, here is the code:
<div className={'mb-8'}>
<Select>
<SelectTrigger className="w-[300px] text-foreground">
<SelectValue/>
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="apples">Apples</SelectItem>
<SelectItem value="bananas">Bananas</SelectItem>
<SelectItem value="mangos">Mangos</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
How to make a default value
to be selected when the component is rendered? For example I want apples
to be selected?
Edit:
It's important to note that there are two ways to use the Select input: controlled and uncontrolled. This solution is for uncontrolled, meaning you don't have to manually store the Select's value. Bersan's answer shows a way to do it the controlled way. Here is a working example that shows both use cases.
Uncontrolled:
export default function ControlledSelect() {
return (
<Select defaultValue="apple">
<SelectTrigger className="w-[300px] text-foreground">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="apple">Apple</SelectItem>
<SelectItem value="banana">Banana</SelectItem>
<SelectItem value="blueberry">Blueberry</SelectItem>
<SelectItem value="grapes">Grapes</SelectItem>
<SelectItem value="pineapple">Pineapple</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
);
}
Controlled:
export default function ControlledSelect() {
const [selectedOption, setSelectedOption] = useState('apple');
return (
<Select
value={selectedOption}
onValueChange={(value) => {
setSelectedOption(value);
}}
>
<SelectTrigger className="w-[300px] text-foreground">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem value="apple">Apple</SelectItem>
<SelectItem value="banana">Banana</SelectItem>
<SelectItem value="blueberry">Blueberry</SelectItem>
<SelectItem value="grapes">Grapes</SelectItem>
<SelectItem value="pineapple">Pineapple</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
);
}
Shadcn's Select component is built with Radix's Select Primitive. There is usually a link at the top of Shadcn's component docs that links to the props for the component. To set a default value on <Select>
, add the defaultValue
prop like this:
<Select defaultValue='apples'>
...
</Select>
You can find more details on the props here.