How can i reset a Select field? #638
Answered
by
schmoli
gmcamposano
asked this question in
Q&A
-
I currently have:
How can i make the select form reset back to the placeholder text? |
Beta Was this translation helpful? Give feedback.
Answered by
schmoli
Jun 22, 2023
Replies: 2 comments 9 replies
-
I did this by adding a button at the end of the list, making sure to change the key assigned to the select so that when I change the value I can force it to re render... here's a simple example: export const SelectDemo = () => {
const [key, setKey] = React.useState(+new Date())
const [value, setValue] = React.useState<string | undefined>(undefined)
return (
<>
<Select key={key} value={value}>
<SelectTrigger>
<SelectValue placeholder="Select a Theme" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel className="-ml-2 text-xs">Category 1</SelectLabel>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="dark">Dark</SelectItem>
<SelectItem value="system">System</SelectItem>
</SelectGroup>
<SelectGroup>
<SelectLabel className="-ml-2 text-xs">Category 2</SelectLabel>
<SelectItem value="cobalt2">Cobalt2</SelectItem>
</SelectGroup>
<SelectSeparator />
<Button
className="w-full px-2"
variant="secondary"
size="sm"
onClick={(e) => {
e.stopPropagation()
setValue(undefined)
setKey(+new Date())
}}
>
Clear
</Button>
</SelectContent>
</Select>
</>
)
} |
Beta Was this translation helpful? Give feedback.
7 replies
Answer selected by
gmcamposano
-
check this snippet added a 'x' icon for clearing, used the same approach as the above ans.
|
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I did this by adding a button at the end of the list, making sure to change the key assigned to the select so that when I change the value I can force it to re render... here's a simple example: