How to set a default value in react-select

392,284

Solution 1

I guess you need something like this:

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

Solution 2

I used the defaultValue parameter, below is the code how I achieved a default value as well as update the default value when an option is selected from the drop-down.

<Select
  name="form-dept-select"
  options={depts}
  defaultValue={{ label: "Select Dept", value: 0 }}
  onChange={e => {
              this.setState({
              department: e.label,
              deptId: e.value
              });
           }}
/>

Solution 3

If you've come here for react-select v2, and still having trouble - version 2 now only accepts an object as value, defaultValue, etc.

That is, try using value={{value: 'one', label: 'One'}}, instead of just value={'one'}.

Solution 4

I was having a similar error. Make sure your options have a value attribute.

<option key={index} value={item}> {item} </option>

Then match the selects element value initially to the options value.

<select 
    value={this.value} />

Solution 5

Extending on @isaac-pak's answer, if you want to pass the default value to your component in a prop, you can save it in state in the componentDidMount() lifecycle method to ensure the default is selected the first time.

Note, I've updated the following code to make it more complete and to use an empty string as the initial value per the comment.

export default class MySelect extends Component {

    constructor(props) {
        super(props);
        this.state = {
            selectedValue: '',
        };
        this.handleChange = this.handleChange.bind(this);

        this.options = [
            {value: 'foo', label: 'Foo'},
            {value: 'bar', label: 'Bar'},
            {value: 'baz', label: 'Baz'}
        ];

    }

    componentDidMount() {
        this.setState({
            selectedValue: this.props.defaultValue,
        })
    }

    handleChange(selectedOption) {
        this.setState({selectedValue: selectedOption.target.value});
    }

    render() {
        return (
            <Select
                value={this.options.filter(({value}) => value === this.state.selectedValue)}
                onChange={this.handleChange}
                options={this.options}
            />
        )
    }
}

MySelect.propTypes = {
    defaultValue: PropTypes.string.isRequired
};
Share:
392,284
user7334203
Author by

user7334203

Updated on April 25, 2022

Comments

  • user7334203
    user7334203 about 2 years

    I have an issue using react-select. I use redux form and I've made my react-select component compatible with redux form. Here is the code:

    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}
            selectedValue={props.selectedValue}
        />
    );
    

    and here how I render it:

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

    But the problem is that that my dropdown has not a default value as I wish. What I'm doing wrong? Any ideas?

    • Ved
      Ved about 7 years
      this is correct: value={props.input.value}. what is the issue you facing?
    • user7334203
      user7334203 about 7 years
      My issue is that i want my select to have a defaultValue when i first render it but i can't
    • Ved
      Ved about 7 years
      what is value of props.input.value when it render first?
    • user7334203
      user7334203 about 7 years
      That's my problem. How to set it to have a default value?
    • Ved
      Ved about 7 years
      what value do you want?
    • user7334203
      user7334203 about 7 years
      i want to have a default value = 'Any'
  • Joseph Juhnke
    Joseph Juhnke almost 7 years
    The point in binding with redux/react is so the ui reflects the value of the object in real time. this approach decouples that binding. Consider setting the default value in the reducer.
  • Ved
    Ved almost 7 years
    @JosephJuhnke check the question first. It is how to set default value.
  • user2026178
    user2026178 almost 7 years
    I think this is the best/most elegant solution. Am I correct in thinking that?
  • raghul
    raghul almost 6 years
    value will not change if do so, you have write onChange function too set change
  • transang
    transang over 5 years
    selectedValue had been changed to value. Check docs react-select.com/props
  • Hongbo Miao
    Hongbo Miao over 5 years
    There is defaultValue field now in the new version.
  • Dennis Liu
    Dennis Liu over 5 years
    Thanks, now i know that defaultValue takes the object instead of just value.
  • Jason Rice
    Jason Rice over 5 years
    I get this: Warning: value prop on select should not be null. Consider using an empty string to clear the component or undefined for uncontrolled components.
  • Alex
    Alex about 5 years
    Not according to React docs or intelisense it doesn't: reactjs.org/docs/uncontrolled-components.html#default-values
  • alexventuraio
    alexventuraio almost 5 years
    I'm doing the same and I'm getting this warning: Warning: A component is changing a controlled input of type hidden to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa).
  • Dan Meigs
    Dan Meigs almost 5 years
    @AlexVentura I've made my code a little more complete and tested it on my system. I don't get the warning about controlled input. Try updating your code based on my edited response and post back what you find.
  • andyCao
    andyCao almost 5 years
    the tricky thing is you need to set the selected object to 'defaultValue' field, instead of the value of the options. e.g. 0,1,2
  • Mike Goatly
    Mike Goatly over 4 years
    This is for a vanilla HTML <select> element, not a react-select <Select>, which is what was question was for. Casing can make all the difference :)
  • Toskan
    Toskan almost 4 years
    incomplete. if you set value to that, you cannot change the valuie any longer
  • eedrah
    eedrah almost 4 years
    @Toskan - yes, this is one of the principles of ReactJS and one-way data binding, and affects all form elements not just this library. You need to handle the change yourself outside of react if you choose to have a Controlled Component. This answer talks about it and links through to the React Docs: stackoverflow.com/questions/42522515/…
  • Toskan
    Toskan almost 4 years
    ok fair enough, so what problem does you solution solve? that is, hard coding a value?
  • eedrah
    eedrah almost 4 years
    The case of {value: 'one', label: 'One'} given here is merely an example. In your application this would be a variable/prop with an identical structure.
  • Rashad Nasir
    Rashad Nasir over 3 years
    @Alex - (and for anyone here 2 years later), this question was in reference to react-select, a component library. The docs you linked to are in reference to native HTML select elements.
  • DanyMartinez_
    DanyMartinez_ over 3 years
    i am function with this: value = {eOptions.filter(option=> option.value == this.state.employmentStatus)} defaultValue={this.state.employmentStatus}
  • Arca Ege Cengiz
    Arca Ege Cengiz about 3 years
    For any future readers, this is probably the best and simplest option. The value prop works without redux too.
  • estani
    estani about 3 years
    @transang this is wrong and very confusing. Setting value will indeed set the value... which you won't be able to change anymore (hardly the desired effect). please remove your comment, or define for which versions it should have worked.
  • Amartya Mishra
    Amartya Mishra about 3 years
    One way data binding doesn't mean data once set from a prop cannot be changed within the child component if so wishes. Which is exactly what will happen if defaultValue is used instead of value
  • Asking
    Asking over 2 years
    @Ved, could you please help with this stackoverflow.com/questions/70187021/…
  • Ved
    Ved over 2 years
    @AskingI will have a look.
  • Qamar
    Qamar over 2 years
    options={props.options} is not required once you done {...props}
  • b.doe
    b.doe over 2 years
    I would kiss you in your behind for this! Thanks man.