ui: Unable to reset the Select component with React Hook Form
Calling form.reset() (React Hook Form reset method) does not reset the value selected by the user in the Select.
Here’s my useForm hook usage:
const form = useForm<z.infer<typeof someSchema>>({
resolver: zodResolver(someSchema),
})
Here’s my submit handler:
async function onSubmit(values: z.infer<typeof someSchema>) {
form.reset()
}
Here’s my Select field:
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
>
<FormField
control={form.control}
name="type"
render={({ field }) => (
<FormItem>
<FormLabel>Type</FormLabel>
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger>
<SelectValue placeholder="Select something" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="A">
A
</SelectItem>
<SelectItem value="B">
B
</SelectItem>
</SelectContent>
</Select>
</FormItem>
)}
/>
<Button type="submit">
Submit
</Button>
</form>
</Form>
About this issue
- Original URL
- State: open
- Created a year ago
- Reactions: 7
- Comments: 35
Try using
valueinstead ofdefaultValueAs a temporary workaround, I have modified the
SelectTriggerto explicitly check thefield.value. If it is not set, it displays your placeholder.You also need to add the
valueprop to theSelectcomponent, as @riyaadh-abrahams suggested, in order to clear the selection when callingform.reset().I have tried this and setting the
defaultValuestoundefined. Whenform.reset()is called, the<Select value={field.value}>doesn’t reset back to the original where the<SelectValue placeholder='Select a role'>.I tried doing this and I does reset the values however it doesn’t the entered value on the input field resulting in something like this
i think you need to pass defaulValues
form.reset(defaultValues)react hook form reset has bug !
use
form.reset, form can’t rerender select. so u can see it not working. butform.setValuecan working and rerender.and how to use it for 100% working
just like this
reset single form item
reset all form item
As @joaom00 said, you need to upgrade to @radix-ui/react-select@2.0.0-rc.9. I got the desired behavior by setting the default value to
""and addingvalue={field.value}to the Select.Hi @asafeclemente , you can change like that. change : defaultValue={field.value} -> value={field.value}
Is there a similar problem with Radio Group? I’m trying to use it in the exact way indicated:
And I’m having the problem that form.reset doesn’t reset this field
I found the problem caused by the
onValueChangeevent inside the form. Try to modifyonChangeValueand usevalueinstead ofdefaultValueHey guys, there is a bug in Radix if you want to reset the value and show the placeholder again. It was fixed in https://github.com/radix-ui/primitives/pull/2174 and you can reset to placeholder using
"". For now, it’s only available on RC https://www.npmjs.com/package/@radix-ui/react-select?activeTab=versions