Sukesh
Sukesh

Reputation: 197

Antd Select not setting initial value

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

Upvotes: 1

Views: 14977

Answers (3)

Salis Khizar Khan
Salis Khizar Khan

Reputation: 51

import { Form, Select } from 'antd';
import { useEffect } from 'react';

const { Option } = Select;

function MyForm() {
  const [form] = Form.useForm();

  const initialValues = {
    mySelect: 'option2',
  };

  useEffect(() => {
    form.setFieldsValue(initialValues);
  }, [form, initialValues]);

  return (
    <Form form={form} initialValues={initialValues}>
      <Form.Item name="mySelect" label="My Select">
        <Select>
          <Option value="option1">Option 1</Option>
          <Option value="option2">Option 2</Option>
          <Option value="option3">Option 3</Option>
        </Select>
      </Form.Item>
    </Form>
  );
}

Upvotes: 1

Benjamin Roberts
Benjamin Roberts

Reputation: 566

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

Upvotes: 0

Tommy Tang
Tommy Tang

Reputation: 72

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

Upvotes: 2

Related Questions