Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a default value in react-select

People also ask

How do I set default value in React select?

To set the default value of the <select> element, you can use the defaultValue attribute in React. Let's look at a sample code. This controlled component sets the default value using the appropriately named defaultValue attribute on the <select> element.

How do I set the default value in select?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

How do you set a selected value in React?

To set selected value of a select drop down to null with React, we can set the state we use as the value of the value prop of the select drop down to null . to set onChange to a function that calls setSelected to e. target. value which is the selected value if it's truthy.


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}
  />
);

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
              });
           }}
/>

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'}.


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} />