How can I reset Form to its initial default state UIKIT

Hi, I am using useForm hook and Form component from UI Kit, On a button click I need to reset the form to its default state. How can I do it?

Hey @SingalRadhika ,

Did you find the solution to this question yet?

If not, I would say the easiest workaround (as there’s no built in way to do this) is to trigger react to remount the form component by giving it a new key - ie

add a variable called formKey

  const [formKey, setFormKey] = useState(0);

Here’s my form:

    <Form key={formKey} onSubmit={handleSubmit(submit)}>
      <FormHeader title="Choose your Cheese">
        Select the type of cheese you'd like to display
      </FormHeader>
      <FormSection>
            <Label labelFor={getFieldId("cheese")}>Pick a cheese</Label>
            <RadioGroup
              {...register("cheese")}
              options={CHEESES}
            />
      </FormSection>
      <FormFooter>
        <Button onClick={handleCancel} appearance="subtle">Cancel</Button>
        <Button onClick={handleReset} appearance="subtle">Reset</Button>
        <Button appearance="primary" type="submit">
          Save
        </Button>
      </FormFooter>
    </Form>

And here’s how I handle the reset:

  const handleReset = () => {
    setFormKey(prev => prev + 1); // This will remount the form
  };

This will work if you’re using a default form value as well.

If this has helped, be sure to mark it as the solution!

Cheers,
Mel

1 Like