I have an issue in setting the initial value in antd Select
const options=[{name:'john',id:1},{name:'jack',id:2},{name:'jill',id:3}]
<Form initialValues={{user:3}}>
<Form.Item name="user" label="Select user">
<Select value="3">
{options.map((user,index)=><Option key={index} value={user.id}>{user.name}</Option>)}
</Select>
</Form.Item>
</Form>
It's not selecting the initial value. Any idea in this. is this a correct way of implementing it, please help
The below is a simple demo of Select Component in Antd Form
I am wondering whether the options come from the store or other components? So the form does not get the initial values once the form is mounted. If it comes from other source, you need to subscribe the initial values if it changes to reset the antd form like
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Checkbox, Select } from 'antd';
const layout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 16,
},
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16,
},
};
// useEffect(() => {
// form.resetFields()
// form.setFieldsValue({
// productName: productName
// })
// }, [initialValues]);
const userNameOptions = [{name:'john',id:1},{name:'jack',id:2},{name:'jill',id:3}]
const Demo = () => {
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
return (
<Form
{...layout}
name="basic"
initialValues={{
remember: true,
username: 3
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="Username"
name="username"
rules={[
{
required: true,
message: 'Please input your username!',
},
]}
>
<Select value='3'>
{userNameOptions.map((item, index) => (
<Select.Option key={index} value={item.id}>
{item.name}
</Select.Option>
))}
</Select>
</Form.Item>
<Form.Item
label="Password"
name="password"
rules={[
{
required: true,
message: 'Please input your password!',
},
]}
>
<Input.Password />
</Form.Item>
<Form.Item {...tailLayout} name="remember" valuePropName="checked">
<Checkbox>Remember me</Checkbox>
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
ReactDOM.render(<Demo />, document.getElementById('container'));
I have this working in ant design 4.
If you only need to set the value once use defaultValue and pass a string prop
defaultValue={!!props.DefaultString && claimId}
You can however set the values for both the current value and the options by using form.setFieldsValue in useEffect.
e.g.
useEffect(() => {
form.setFieldsValue({
SelectValue: !!props.selectItemValue && props.props.claimId,
SelectableOptions: (!!props.selectableOptions? props.selectableOptions : undefined)
);
}
}, [props,form]);
<Form.Item name="SelectValue" >
<Select >
{!!props.selectableOptions && props.selectableOptions.map((opt) => <Option key={opt.id} value={opt.id}>{opt.name}</Option>)}
</Select>
</Form.Item>
NB: Use the props directly rather than the fieldValue for the options
Related
It seems that we couldn't add validation for antd editable <Text> (typography).
The component doesn't accept value props like <Input> component. How do we do validation in that case?
Code:
const [title, setTitle] = useState("Battle");
<>
<Form id="myForm" name="basic" onFinish={onSubmit}>
<Form.Item
name="title"
rules={[
{
required: true,
message: "Please input your title!"
}
]}
>
<Text editable>{title}</Text>
</Form.Item>
</Form>
<Button form="myForm" key="formSubmit" htmlType="submit" type="primary">
Create
</Button>
</>
Above code validation works but if the data is still there, it show validation error.
Codesandbox link : https://codesandbox.io/s/basic-antd-4-16-9-forked-o8nxdl?file=/index.js
Here is a code that does some simple validations
function reducer (action , state) {
switch (action.type){
case 'title':
return {...state , data : { ...state.data , title : action.payload }
, errors : { ...state.errors
, title : title.length > 3 null : '😈'} } // title length must be > 3
}
}
const [state , dispatch] = useReducer (reducer , {data : {} , errors : {})
console.log (state)
return ( <> <Form.Item
name="title"
rules={[
{
required: true,
message: "Please input your title!"
}
]}
onChange = {(e) => dispatch ({type : 'title' , payload : e.target.value})
>
<Text editable>{title}</Text>
</Form.Item> </>)
Before submitting make sure all errors must be null
you can handle it using the onChange like this working demo is here
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Button, Input, Typography } from "antd";
import SecForm from "./SecForm";
const { Text } = Typography;
const App = () => {
const [title, setTitle] = useState('Battle');
const data = ["1", "2", "3"];
const onHandleChange = (event) => {
setTitle(event);
};
const onSubmit = (e) => {
e.preventDefault();
console.log("Submitted");
};
return (
<>
<Form id="myForm" name="basic" onFinish={onSubmit}>
<Form.Item
label="name"
name="name"
rules={[
{
required: true,
message: "Please input your name!"
}
]}
>
<Input placeholder="Name" />
</Form.Item>
<Form.Item
label="rank"
name="rank"
rules={[
{
required: true,
message: "Please input your rank!"
}
]}
>
<Input placeholder="Rank" />
</Form.Item>
<Form.Item
name="title"
valuePropName={title}
rules={[
{
required: title?.length < 1,
message: "Please input your title!"
}
]}
>
<Text editable={{ onChange: onHandleChange }}>{title}</Text>
</Form.Item>
{data.map((d, index) => (
<SecForm index={index} />
))}
</Form>
<Button form="myForm" key="formSubmit" htmlType="submit" type="primary">
Create
</Button>
</>
);
};
ReactDOM.render(<App />, document.getElementById("container"));
I have a antd form that consists of input and checkboxes.
antd : 4.16.0
react : 17.0.2
After using,
this.formRef.current.resetFields();
the input fields are getting reset but not the checkboxes.
Sample Code:
<Form
layout="vertical"
hideRequiredMark
initialValues={{
sunH: [
moment("00:00", "HH:mm"),
moment("00:00", "HH:mm"),
],
monH: [
moment("00:00", "HH:mm"),
moment("00:00", "HH:mm"),
],
}}
ref={this.props.formRef}
>
<Row gutter={16}>
<Col span={12}>
<Form.Item
name="pName"
label="Name"
rules={[
{
required: true,
message: "Please enter Name",
},
]}
>
<Input placeholder="Enter name" />
</Form.Item>
<Form.Item name="Mon" label="" valuePropName="checked">
<Text>Mon</Text>
</Form.Item>
</Col>
</Row>
</Form>
the form takes in a onCancel props, so onCancel,
this.formRef.current.resetFields();
log of this.formRef.current:
you can manually set radio fields value null in that function ...
all you have to do is ...
formRef.setFieldsValue(['label_name(Mon)'] : undefined)
try formRef.current.setFieldsValue if you cant't change using upper code.
for functional component you have to take the form reference that is binding using useForm() and you have to call setfield method same.
form.setFieldsValue(['label_name(Mon)'] : undefined )
ant.design/components/form/#components-form-demo-nest-messages Check the second example, they have well explained everything you need there
https://codesandbox.io/s/form-methods-antd-4-17-0-alpha-7-forked-ff1uf?file=/index.js:0-2953
Check this working example with checkbox
import React from "react";
import ReactDOM from "react-dom";
import "antd/dist/antd.css";
import "./index.css";
import { Form, Input, Button, Select, Checkbox } from "antd";
const { Option } = Select;
const layout = {
labelCol: {
span: 8
},
wrapperCol: {
span: 16
}
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16
}
};
const Demo = () => {
const [form] = Form.useForm();
const onGenderChange = (value) => {
switch (value) {
case "male":
form.setFieldsValue({
note: "Hi, man!"
});
return;
case "female":
form.setFieldsValue({
note: "Hi, lady!"
});
return;
case "other":
form.setFieldsValue({
note: "Hi there!"
});
}
};
const onFinish = (values) => {
console.log(values);
};
const onReset = () => {
form.resetFields();
};
const onFill = () => {
form.setFieldsValue({
note: "Hello world!",
gender: "male"
});
};
return (
<Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
<Form.Item
name="note"
label="Note"
rules={[
{
required: true
}
]}
>
<Input />
</Form.Item>
<Form.Item
name="gender"
label="Gender"
rules={[
{
required: true
}
]}
>
<Select
placeholder="Select a option and change input text above"
onChange={onGenderChange}
allowClear
>
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) =>
prevValues.gender !== currentValues.gender
}
>
{({ getFieldValue }) =>
getFieldValue("gender") === "other" ? (
<Form.Item
name="customizeGender"
label="Customize Gender"
rules={[
{
required: true
}
]}
>
<Input />
</Form.Item>
) : null
}
</Form.Item>
<Form.Item
name="remember"
valuePropName="checked"
wrapperCol={{
offset: 8,
span: 16
}}
>
<Checkbox>Remember me</Checkbox>
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
<Button htmlType="button" onClick={onReset}>
Reset
</Button>
<Button type="link" htmlType="button" onClick={onFill}>
Fill form
</Button>
</Form.Item>
</Form>
);
};
I am working on a React project, For designing I am using Ant design framework. I have a form in that form when I entered all details in Input form and when I click submit button the Form has to be Reset, I tried to Reset a form after clicking submit button. but it is showing this kind of error. TypeError: Cannot read property 'reset' of null
So please help me to resolve this error
This is my code App.js
import React, { useRef, useState } from "react";
import { Row, Col, Button, Card, Form, Input, Select } from "antd";
import axios from 'axios'
import 'antd/dist/antd.css';
import {
SearchOutlined,
StopOutlined,
UserOutlined,
LeftOutlined,
DoubleRightOutlined,
} from "#ant-design/icons";
import './App.css';
const App = () => {
const { Option } = Select;
const [data, setData] = useState({});
const testData = async () => {
try {
const res = await axios.post('http://localhost:8000/api/user', data);
console.log(res);
} catch (error) {
console.log(error);
}
}
const handleChange = ({ target }) => {
const { name, value } = target;
const newData = Object.assign({}, data, { [name]: value });
setData(newData);
}
const handleSubmit = (e) => {
e.preventDefault();
console.log(data);
testData()
};
const myForm = useRef(null)
const resetForm = () => {
myForm.current.reset();
}
const prefixSelector = (
<Form.Item name="prefix" noStyle>
<Select
style={{
width: 50,
// height: 10,
}}
>
<Option value="86">+86</Option>
<Option value="87">+87</Option>
</Select>
</Form.Item>
);
return (
<div>
<div className="customizedCards">
<Card className="cardStyle">
<div className="main-form">
<h5 className="idDetails">StudentDETAILS</h5>
<Form style={{marginLeft: "-10px"}} ref={myForm}>
<Form.Item
name="name"
noStyle
rules={[{ required: true, message: 'firstname is required' }]}
>
<Input type="text" name='first_name' style={{ width: 400 }} onChange={handleChange} placeholder="Firstname" />
</Form.Item>
<Form.Item
name="name"
noStyle
rules={[{ required: true, message: 'lastname is required' }]}
>
<Input type="text" name='last_name' style={{ width: 400 }} onChange={handleChange} placeholder="Lastname" />
</Form.Item>
<Form.Item
name="name"
noStyle
rules={[{ required: true, message: 'email is required' }]}
>
<Input type="email" name='email' style={{ width: 400 }} onChange={handleChange} placeholder="Email" />
</Form.Item>
<Form.Item
name="phone"
rules={[
{
required: true,
message: 'Please input your phone number!',
},
]}
>
<Input type="number" name='phone_number' addonBefore={prefixSelector} style={{ width: 400 }} onChange={handleChange} placeholder="Phone Number" />
</Form.Item>
<Button onClick={(e) => handleSubmit(e), resetForm()} className="submit" type="primary" >Submit</Button>
</Form>
</div>
</Card>
</div>
</div>
)
}
export default App
```
As said here you just have a syntax trouble.
Try this instead:
const myForm = useRef(null)
const resetForm = () => {
myForm.reset();
}
Im using my project for React ant design 4 . I have some conflict on the form . I want to know how to reset only one (Note) field any one know the solution
Thanks
stazkblitz here
code here
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Select } from 'antd';
const { Option } = Select;
const layout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 16,
},
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16,
},
};
const Demo = () => {
const [form] = Form.useForm();
const onGenderChange = (value) => {
switch (value) {
case 'male':
form.setFieldsValue({
note: 'Hi, man!',
});
return;
case 'female':
form.setFieldsValue({
note: 'Hi, lady!',
});
return;
case 'other':
form.setFieldsValue({
note: 'Hi there!',
});
return;
}
};
const onFinish = (values) => {
console.log(values);
};
const onReset = () => {
form.resetFields();
};
const onFill = () => {
form.setFieldsValue({
note: 'Hello world!',
gender: 'male',
});
};
return (
<Form {...layout} form={form} name="control-hooks" onFinish={onFinish}>
<Form.Item
name="note"
label="Note"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
<Form.Item
name="gender"
label="Gender"
rules={[
{
required: true,
},
]}
>
<Select
placeholder="Select a option and change input text above"
onChange={onGenderChange}
allowClear
>
<Option value="male">male</Option>
<Option value="female">female</Option>
<Option value="other">other</Option>
</Select>
</Form.Item>
<Form.Item
noStyle
shouldUpdate={(prevValues, currentValues) => prevValues.gender !== currentValues.gender}
>
{({ getFieldValue }) => {
return getFieldValue('gender') === 'other' ? (
<Form.Item
name="customizeGender"
label="Customize Gender"
rules={[
{
required: true,
},
]}
>
<Input />
</Form.Item>
) : null;
}}
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
<Button htmlType="button" onClick={onReset}>
Reset
</Button>
<Button type="link" htmlType="button" onClick={onFill}>
Fill form
</Button>
</Form.Item>
</Form>
);
};
ReactDOM.render(<Demo />, document.getElementById('container'));
You can add an array of namePath in your form.resetFields call
const onReset = () => {
form.resetFields(["note"]);
};
Just tested it with your code and it works : https://stackblitz.com/edit/react-nazmet-jh2cc1?file=index.js
More info : https://ant.design/components/form/#FormInstance
Im using my university project for the react typescript and ant design 4, I have some conflict on this. here the my conflict
I have a Select option 1) Year End Date 2) Year Month End Date.so when it loading first any one know how to disable when the loading Year End Date and need to disable end date select option
any solution for this
stazkblitz here
here the my code
import React from 'react';
import ReactDOM from 'react-dom';
import 'antd/dist/antd.css';
import './index.css';
import { Form, Input, Button, Checkbox,Select } from 'antd';
const layout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 16,
},
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16,
},
};
const { Option } = Select
const Demo = () => {
const onFinish = (values) => {
console.log('Success:', values);
};
const onFinishFailed = (errorInfo) => {
console.log('Failed:', errorInfo);
};
function onChange(value) {
console.log(`selected ${value}`);
}
function onBlur() {
console.log('blur');
}
function onFocus() {
console.log('focus');
}
function onSearch(val) {
console.log('search:', val);
}
return (
<Form
{...layout}
name="basic"
initialValues={{
remember: true,
}}
onFinish={onFinish}
onFinishFailed={onFinishFailed}
>
<Form.Item
label="Year End date"
name="YearEndDate"
rules={[
{
required: true,
message: 'Please select date type!',
},
]}
>
<Select
showSearch
style={{ width: 200 }}
placeholder="Select a Year End date"
optionFilterProp="children"
onChange={onChange}
onFocus={onFocus}
onBlur={onBlur}
onSearch={onSearch}
filterOption={(input, option) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
<Option value="yDate">Year End Date</Option>
<Option value="yDM">Year Month End Date</Option>
</Select>,
</Form.Item>
<Form.Item
label="End Date"
name="endDate"
rules={[
{
required: true,
message: 'Please seelct date!',
},
]}
>
<Select
showSearch
style={{ width: 200 }}
placeholder="Select a date"
optionFilterProp="children"
onChange={onChange}
onFocus={onFocus}
onBlur={onBlur}
onSearch={onSearch}
filterOption={(input, option) =>
option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
<Option value="date1">28</Option>
<Option value="date2">30</Option>
<Option value="date3">31</Option>
</Select>
</Form.Item>
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit">
Submit
</Button>
</Form.Item>
</Form>
);
};
If I've understood your question correctly, what you're asking is "how to disable "End Date " field, if the value of the "Year End date" field is "Year End Date" or when the component is first loading.
If that is the case, you can use react hooks to find the value of the "Year End Date" field and use it to disable the second field
Here's your code with the hook added: https://stackblitz.com/edit/react-xekm8s-plyist?file=index.js