Asking
Asking

Reputation: 4192

Add default value option in select tag

I use a select tag in my application:

<Select
    showSearch={false}
    defaultValue={["Lucy"]}
    mode="multiple"
    style={{ width: 200 }}
    placeholder="Select a person"
    optionFilterProp="children"
    onChange={onChange}
    onFocus={onFocus}
    onBlur={onBlur}
    onSearch={onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="jack">Jack</Option>
    <Option value="lucy">Lucy</Option>
    <Option value="tom">Tom</Option>
  </Select>,
  document.getElementById("container")

I want to set a default selected value for this Select, to get something like this:
enter image description here


So, when i will open first time this dropdown, i want to have a default value selected in the way like in the image. I tried defaultValue but it does not work as i described., So, how to achive what i described above?
demo: https://codesandbox.io/s/select-with-search-field-ant-design-demo-4f9op?file=/index.js:410-955

Upvotes: 0

Views: 50

Answers (2)

Michael Mishin
Michael Mishin

Reputation: 571

The option value is 'lucy', and you set the default value to 'Lucy' (with a capital letter). Therefore, the default value does not work. Set the default value to 'lucy'.

Upvotes: 1

subashMahapatra
subashMahapatra

Reputation: 6837

You are providing ['Lucy'] (uppercased) as default value but the values provided in the options are 'lucy', 'jack', and 'tom' all lowercased. That is why the Select treats the default value as another value.

Solution either provide the default value same as used in options defaultValue={["lucy"]} or use uppercased values in Option if you want the defaultValue to be uppercased as well.

<Select
    showSearch={false}
    defaultValue={["lucy"]}
    mode="multiple"
    style={{ width: 200 }}
    placeholder="Select a person"
    optionFilterProp="children"
    onChange={onChange}
    onFocus={onFocus}
    onBlur={onBlur}
    onSearch={onSearch}
    filterOption={(input, option) =>
      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
    }
  >
    <Option value="jack">Jack</Option>
    <Option value="lucy">Lucy</Option>
    <Option value="tom">Tom</Option>
  </Select>,
  document.getElementById("container")

Codesandbox demo, codesandbox

Upvotes: 1

Related Questions