Reputation:
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
Reputation: 409
form.resetFields()
will reset all form fields.
To reset a particular form field form.resetFields([formItemName])
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
Reputation: 65
form.resetFields()
...
onChange={() => form.setFieldsValue({ name: '' })}
...
Upvotes: 2
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
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
Reputation: 11
Upvotes: 1
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);
Hope it helps :)
Upvotes: 26