React | Ant design select default value

Selvin picture Selvin · Sep 20, 2018 · Viewed 30.8k times · Source

I'm using ant design in my project.

Here I have a select as a dynamic field. when I trying to set default value for select. It doesn't work.

<Select defaultValue="lucy">
  <Option value="jack">Jack</Option>
  <Option value="lucy">Lucy</Option>
  <Option value="Yiminghe">yiminghe</Option>
</Select>

I'm setting defaultvalue as lucy But it doesn't work

Reproduction Code: https://codesandbox.io/s/6x3qv6wymr

Answer

Triyugi Narayan Mani picture Triyugi Narayan Mani · Sep 21, 2018

According to the documentation, you should not use value or defaultValue with getFieldDecorator.

After wrapped by getFieldDecorator, value(or other property defined by valuePropName) onChange(or other property defined by trigger) props will be added to form controls,the flow of form data will be handled by Form which will cause:

  1. You shouldn't use onChange to collect data, but you still can listen to onChange(and so on) events.

  2. You can not set value of form control via value defaultValue prop, and you should set default value with initialValue in getFieldDecorator instead.

  3. You shouldn't call setState manually, please use this.props.form.setFieldsValue to change value programmatically.

So, in your code you need to define initialValue instead of defaultValue as given below:

{getFieldDecorator(`names[${k}]`, {
        validateTrigger: ["onChange", "onBlur"],
        initialValue: "lucy",
        rules: [
          {
            required: true,
            whitespace: true,
            message: "Please input passenger's name or delete this field."
          }
        ]
      })(
        <Select>
          <Option value="jack">Jack</Option>
          <Option value="lucy">Lucy</Option>
          <Option value="Yiminghe">yiminghe</Option>
        </Select>
      )}

You can check the working demo on codesandbox.io.