Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 464
user7334203 Avatar asked Jul 29 '26 02:07

user7334203


1 Answers

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!

like image 125
RemEmber Avatar answered Jul 30 '26 16:07

RemEmber



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!