简体   繁体   中英

Default Value in react-select

i have a react-select component which i made compatible with redux-form. My SelectInput component is this:

const MySelect = props => (
  <Select
    {...props}
    value={props.input.value}
    onChange={value => props.input.onChange(value)}
    onBlur={() => props.input.onBlur(props.input.value)}
    options={props.options}
    placeholder={props.placeholder}
  />
);

and i render it in my component which is a form

<div className="select-box__container">
                <Field
                  id="side"
                  name="side"
                  component={SelectInput}
                  options={sideOptions}
                  value="Any"
                  clearable={false}
                  // placeholder="Select Side"
                />
              </div>

I've also set initial values to the container so as the state for this component has an initial value and it's working. My problem is that when i render the component the initial value does not show in the selection box and it's empty. Why is this happenning?

What is the shape of your options ? - commonly it is an array of objects with a value and a label property:

[
  { label: "I like", value: "icecream" },
  { label: "Any", value: "Any" }
]

You can set the initial value prop of react-select by setting it to one of the values in your options array. Alternatively, you can as well set it to a non existing option, by giving it an object with a label and a value. The label is what is displayed as the value of the select. Indeed a little bit confusing, though it makes kind of some sense.

TL;DR

value={{ value: 0, label: 'Any' }} - will do the trick!

You can as well set the initial value to a value of your options and it will get displayed. Meaning if you have { value: "Any", label: "Any" } in your options value={'Any'} would display "Any" in the select.

Hope this works for you!

Ran into a similar issue. The input value field is constantly unset even though it is properly passed. You can either create an input object that has a value prop (and all other required props) or use a separate prop selectedValue in this case.

 <Field
  id="side"
  name="side"
  component={SelectInput}
  options={sideOptions}
  value="Any"
  clearable={false}
  selectedValue={this.props.myvalue}
 />

const MySelect = props => (
  <Select
   {...props}
   value={(props.input.value) ? props.input.value : props.selectedValue}
   onChange={value => props.input.onChange(value)}
   onBlur={() => props.input.onBlur(props.input.value)}
   options={props.options}
   placeholder={props.placeholder}
  />
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM