'default value for multiple select in form antd 4

I'm unable to set default value for multi select inside form.

Use Case: I have created a react component that renders a select with some default props that I need in every form. Now I want to set default value for that select from the defaultValue prop of select instead of passing initialValues to every form.

My react component looks like:

import React, { Component } from 'react';
import { Form, Select } from 'antd';

class FormSelect extends Component {
  render() {
    const {name, label, rules, onSelect, disabled, options, mode} = this.props;

    let defaultValue;
    if (mode === 'tags' || mode === 'multiple'){
      defaultValue = [];
    }

    return (
      <Form.Item
        hasFeedback
        name={name}
        label={label}
        rules={rules}
      >
        <Select
          showSearch
          mode={mode}
          tokenSeparators={[',']}
          defaultValue={defaultValue}
          onSelect={onSelect}
          disabled={disabled}
        >
          {
            options.map((op) => (
              <Select.Option key={op.value} value={op.value} label={op.label}>
                {op.label}
              </Select.Option>
            ))
          }
        </Select>
      </Form.Item>
    );
  }
}
export default FormSelect;

The problem is when I set the defaultValue prop of select the value is shown in UI but when the form is submitted the defaultValue is ignored and value of select field remains undefined



Solution 1:[1]

Form.Item now supports initialValue prop in version 4.2.2 which can be used to set default value.

Solution 2:[2]

If I get your question right, you need to do something like this in the callback of your options.map():

<Select.Option
  selected={op.value === this.props.defaultValue ? true : false}
  key={op.value}
  value={op.value}
  label={op.label}>
    {op.label}
</Select.Option>

Explanation: If op.value of an option is equal to the defaultValue passed as props, that option will be selected by default.

React is smart enough to know whether to add selected attribute to a particular option or not based upon its value being true or false.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Piyush Kakkar
Solution 2