ShinChven's Blog

Reset Form Fields in Shared Ant Design Modal Form

Thu Nov 17 2022

I use shared ModelForm in my project for a selected target in multiple rows of data to keep good page rendering performance. But a shared ModelForm has a problem that it can't reset form fields after editing is done. So I have to do it manually.

This trick is also working in DrawerForm or customized Modal or Drawer.

Here's how I do it:

import React, {useEffect} from "react";
import {Form} from "antd";
import {ProFormText} from "@ant-design/pro-form";
import {ModalForm} from "@ant-design/pro-components";

type UserModel = {
  email?: string;

type EditUserFormProps = {
  user?: UserModel;
 * A shared ModalForm for editing user
 * @param user the editing target, may change.
 * @constructor
const EditUserForm: React.FC<EditUserFormProps> = ({user}) => {
  // The form instance
  const [form] = Form.useForm<Partial<UserModel>>();

  // Subscribe to user object changes
  const resetKey = user?.id || 0;
  useEffect(() => {
    // Reset form fields,
  }, [resetKey]); // if the user changed.

  return <ModalForm<Partial<UserModel>>
    <ProFormText name='email' initialValue={user?.email}/>

export default EditUserForm;