user9348468
user9348468

Reputation:

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

I was created a registration page using react. There I have used this following registration form. https://ant.design/components/form. All the validation were handled properly and after successful attempt user can register to the system. Only problem I have faced is, unable to clear the form input field values after the submission.

I have implemented a method to clear the form field values to null. But it was not working. And I tried out previous similar questions in stackoverflow, but still couldn't get a workable one for me. Reason for that may be since I am using the ant design template.

this.setState({
        confirmDirty: false,
        autoCompleteResult: [],
        userName: '',
        email: '',
        experience: [],
        password: ''
})

Above code is to clear the input values. But it was not working and the all the form input fields values remained save. Below is the part of the registration form code.

class RegistrationForm extends React.Component {
state = {
    confirmDirty: false,
    autoCompleteResult: [],
    userName: '',
    email: '',
    experience: [],
    password: ''
};
//below form is inside the render method and return 
<Form onSubmit={this.handleSubmit}>
  <FormItem
    {...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 />
     )}
  </FormItem>
</Form>
  handleSubmit = (e) => {
      e.preventDefault();
      this.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //submission done
          //then execute the above code which I mentioned previously in the question, to reset the input fields value

        }
      });
  }
  }

Where I could get wrong and how can I resolve this?

Upvotes: 29

Views: 121445

Answers (6)

Ankit Tailor
Ankit Tailor

Reputation: 409

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;

Upvotes: 24

congdc
congdc

Reputation: 65

  1. the simplest way to reset the entire form you use resetForm().
form.resetFields()
  1. For those inputs you want to change the default value, you can specify it using setFieldsValue().
...
onChange={() => form.setFieldsValue({ name: '' })}
...

Upvotes: 2

azeem
azeem

Reputation: 361

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}));
      }
  }

Upvotes: 6

aldel
aldel

Reputation: 6748

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.

Upvotes: 35

Qousar bashir
Qousar bashir

Reputation: 11

  1. Create a new Button and set the onclick().
  2. Then call this.props.form.resetFields() in onclick of the button which you created above.
  3. For this whole you need to export your component as export default Form.create()(YourComponent);

Upvotes: 1

Arun AK
Arun AK

Reputation: 4370

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 :)

Upvotes: 26

Related Questions