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

M.Cooper picture M.Cooper · Dec 25, 2018 · Viewed 33.9k times · Source

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?

Answer

Thinker picture Thinker · Dec 25, 2018

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