Clear form input field values after submitting in react js with ant-design

form.resetFields() will reset all form fields.

To reset a particular form field form.resetFields([formItemName])

FormInstance

import React, { useState } from "react";
import { Form, Input } from "antd";

const myComp = () => {
  const [form] = Form.useForm();
  const [val, setVal] = useState("");

  const handleCancel = () => {
    form.resetFields();    //reset form
  };

  const handleOk = async (e) => {
      form.resetFields();    //reset form
  };

  const handelChange = async (e) => {
      setVal(e.target.value);
      if(val.length > 10) {
        form.resetFields(["textField"]); //reset particular field
      }
  };

  return (
      <Form
        form={form}
        name="dynamic_ruleEdit"
        onFinish={handleOk}
      >
        <Form.Item
          name="textField"
          label="Enter your details"
          rules={[
            {
              message: "Enter details",
              required: true,
            },
          ]}
        >
          <Input
            value={val}
            placeholder="Enter details"
            onChange={handelChange}
          />
        </Form.Item>
      </Form>
  );
}
export default myComp;

In a function component, you can very easily get access to the form using the Form.useForm hook. The value returned by this hook should be passed as the form property of the Form component. Then you can just call resetFields on the form in whatever callback you want to clear the form. This example will clear the form when it is submitted:

import React from 'react';
import { Button, Form, Input } from 'antd';

export default function MyFormComponent() {
  const [form] = Form.useForm();

  const submitForm = ({ name, favoriteColor }) => {
    console.log(name, favoriteColor);
    form.resetFields();
  };

  return (
    <Form
      form={form}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 12 }}
      onFinish={submitForm}
    >
      <Form.Item name="name" label="What is your name?">
        <Input />
      </Form.Item>
      <Form.Item name="favoriteColor" label="What is your favorite color?">
        <Input />
      </Form.Item>
      <Form.Item wrapperCol={{ offset: 6, span: 12 }}>
        <Button type="primary" htmlType="submit">
          Submit
        </Button>
      </Form.Item>
    </Form>
  );
}

This only works in antd 4.x and later. Forms seem to have been much more difficult to work with in earlier versions.


We can clear the form data using the resetFields function present in form props given by the ant design library.

After the form is submitted successfully, use this.props.form.resetFields() to clear the data in the form.

Code:

const { Form, Input, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete, } = antd;

const { Option } = Select;
const AutoCompleteOption = AutoComplete.Option;

class RegistrationForm extends React.Component {
  state = {
    confirmDirty: false,
    autoCompleteResult: [],
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
      }
    });
  }

  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const { autoCompleteResult } = this.state;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    };

    return (
      <Form onSubmit={this.handleSubmit}>
        <Form.Item
          {...formItemLayout}
          label="E-mail"
        >
          {getFieldDecorator('email', {
            rules: [{
              type: 'email', message: 'The input is not valid E-mail!',
            }, {
              required: true, message: 'Please input your E-mail!',
            }],
          })(
            <Input />
          )}
        </Form.Item>
        <Form.Item
          {...formItemLayout}
          label="Password"
        >
          {getFieldDecorator('password', {
            rules: [{
              required: true, message: 'Please input your password!',
            }, {
              validator: this.validateToNextPassword,
            }],
          })(
            <Input type="password" />
          )}
        </Form.Item>
        <Form.Item {...tailFormItemLayout}>
          {getFieldDecorator('agreement', {
            valuePropName: 'checked',
          })(
            <Checkbox>I have read the <a href="">agreement</a></Checkbox>
          )}
        </Form.Item>
        <Form.Item {...tailFormItemLayout}>
          <Button type="primary" htmlType="submit">Register</Button>
        </Form.Item>

        <Form.Item {...tailFormItemLayout}>
          <Button onClick={e => {
this.props.form.resetFields()
                          }} >Clear</Button>
        </Form.Item>
      </Form>
    );
  }
}

const WrappedRegistrationForm = Form.create()(RegistrationForm);

ReactDOM.render(<WrappedRegistrationForm />, mountNode);

Live Demo

Hope it helps :)


Very Simple Solution: Just put this line in the functional component

const [form] = Form.useForm();

<Form
            form={form}
            name="normal_login"
            className="login-form"
            initialValues={{
            remember: true,
            }}
/>

After than call the form into onFinish() function.

const onFinish=(values)=>{
     
      form.resetFields();
      let array1=[];
      if(Array.isArray(array1)){
        array1=values;
        localStorage.setItem(`${id}`,JSON.stringify({id,...array1}));
      }
  }