Published on

How to Reset Selected Value in ShadCN UI Select

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Reset Selected Value of Select Option in ShadCN UI

When working with ShadCN UI's <Select> component in a React project, you may encounter a scenario where you need to reset the selected value after a form submission. This article demonstrates how to achieve that using React Hook Form and a clean reset process.

Problem

After submitting a form, you may notice that the selected value in the <Select> component remains unchanged. Clearing the associated state might not reset the visual selection in the UI.

Solution

To reset the <Select> component, we can use the following steps:

  1. Use value and defaultValue Together: Bind the <Select> component to the form field values using both value and defaultValue.
  2. Utilize form.reset(defaultValues): Leverage React Hook Form's reset method to clear the form fields and reset the UI.

Here is a complete implementation:

Code Example

import { zodResolver } from "@hookform/resolvers/zod";
import { SubmitErrorHandler, SubmitHandler, useForm } from "react-hook-form";
import * as z from "zod";

import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toast } from "@/components/ui/use-toast";

// Define validation schema
const FormSchema = z.object({
  email: z
    .string({
      required_error: "Please select an email to display.",
    })
    .email(),
});

const defaultValues = {
  email: "",
};

export function SelectForm() {
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues,
  });

  const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = (data) => {
    toast({
      title: "You submitted the following values:",
      description: (
        <pre className="mt-2 w-[340px] rounded-md bg-slate-950 p-4">
          <code className="text-white">{JSON.stringify(data, null, 2)}</code>
        </pre>
      ),
    });
    form.reset(defaultValues);
  };

  const onError: SubmitErrorHandler<z.infer<typeof FormSchema>> = (data) => {
    console.log(data, "error");
    toast({
      title: "You have error:",
      description: (
        <pre className="mt-2 w-[340px] rounded-md bg-red-700 p-4">
          {data.email?.message}
        </pre>
      ),
    });
  };

  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit, onError)}
        className="w-2/3 space-y-6"
      >
        <FormField
          control={form.control}
          name="email"
          render={({ field }) => (
            <FormItem>
              <FormLabel>Email</FormLabel>
              <Select
                onValueChange={field.onChange}
                value={field.value}
                defaultValue={field.value}
              >
                <FormControl>
                  <SelectTrigger>
                    <SelectValue placeholder="Select a verified email to display" />
                  </SelectTrigger>
                </FormControl>
                <SelectContent>
                  <SelectItem value="[email protected]">m@example.com</SelectItem>
                  <SelectItem value="[email protected]">m@google.com</SelectItem>
                  <SelectItem value="[email protected]">m@support.com</SelectItem>
                </SelectContent>
              </Select>
              <FormMessage />
            </FormItem>
          )}
        />
        <Button type="submit">Submit</Button>
      </form>
    </Form>
  );
}

Key Points

  • Validation: Use Zod for schema-based validation.
  • Form Reset: Call form.reset(defaultValues) to clear the form, including the <Select> component.
  • Value Binding: Use value and defaultValue together to maintain sync between state and UI.

FAQs

Why doesn't clearing the state reset the <Select> component?

ShadCN UI's <Select> component relies on controlled or uncontrolled states. Simply clearing the state may not update the UI without explicitly resetting the associated form field.

Can I use this approach without React Hook Form?

Yes, but you will need to manage the state explicitly using useState and update the value prop of the <Select> manually.

What if I need to reset multiple fields?

React Hook Form's reset method allows you to reset multiple fields simultaneously by providing default values for all fields.

Conclusion

By combining React Hook Form with ShadCN UI components, you can effectively manage form state and reset form fields, including <Select> components, after submission. This ensures a seamless user experience and clean state management.