Setting a default value with react-select not working

白昼怎懂夜的黑 提交于 2020-12-08 07:25:58

问题


I have a simple React component which gets an initial state:

this.state = {
  currentObject: {
    isYounger: false
  }
}

I then render a react-select with the default value of this.state.currentObject.isYounger:

    <Select
      name={"age"}
      value={this.state.currentObject.isYounger}
      onChange={newValue => this.addIsYoungerValue(newValue)}
      options={isYoungerOptions}
    />

For some reason, the value is not set. Why is this?

Codesandbox

Version:

"react-select": "^2.4.2",


回答1:


Here the issue is not with state selection, the actual issue is that the label is not getting displayed.

So, as per your addIsYoungerValue function you are setting the value of this.state.currentObject.isYounger to whole object. i.e. { value: true, label: "Younger" }. So, the issue can be solved by changing the value of initial state by below.

this.state = {
      array: [],
      currentObject: {
        isYounger: { value: true, label: "Younger" }
      }
    };

And hurrey, the default value label will be shown..




回答2:


Your defaultValue or value must be objects. In your case like this:

defaultValue={isYoungerOptions[0]}

or

this.state = {
   array: [],
   currentObject: {
     isYounger: { value: "true", label: "Younger" }
   }
 };

Here an live example.




回答3:


There is an alternate way to use value as your defaultValue. In my case I have used "id" and "industry" instead of "label" and "value"

this.state = {
     interested_industries: [{id:"ANY", industry:"ANY"}]
}

And in Select component:-

<Select 
    name="interested_industries"
    options={industries}
    value={interested_industries}
    getOptionLabel={ x => x.id}
    getOptionValue={ x => x.industry}
    onChange={this.handleSelect}
    isMulti
/>


来源:https://stackoverflow.com/questions/55460443/setting-a-default-value-with-react-select-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!