0

I am trying to set a default value in my select tag so that on every onChange event I can call an API which is my requirement.

I searched online on how to set defaultvalue for select tag, people suggested to use defaultValue attribute which did not work for me.

    let serviceProviderLocationNames = this.props.serviceProviderLocationName.map((location, key) => {
        return <option key={key} value={location.SERVICE_PROVIDER_LOCATION_ID}>{location.DESCRIPTION}</option>
    });
<select
  defaultValue = {{ label: "Select", value: 0}}
  name="serviceProviderLocationDropDown"
  onChange={this.updateServiceProviderLocationId}
>
  {serviceProviderLocationNames}
</select>

I expected to see a "select" value as default and others to be the values that I got from an API, but I couldn't see the "select"

Joseph D.
  • 11,804
  • 3
  • 34
  • 67
  • {serviceProviderLocationNames} This is how I am trying to render the dropdown on UI – Navya Naidu Chamidisetty Aug 04 '19 at 22:05
  • Possible duplicate of [How can I set the default value for an HTML – Adriano Aug 05 '19 at 02:12

3 Answers3

0

Try using the defaultValue parameter.

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

To see Select by default, you need to add an option before your original option as,

<select
  value={this.state.selectedValue} //Add the selected value here, may be from state. For example `this.state.selectedValue` you can change the name whatever you have
  name="serviceProviderLocationDropDown"
  onChange={this.updateServiceProviderLocationId}
>
  <option>Select</option>   //By default selected
  {serviceProviderLocationNames}
</select>

onChange of your select you have updateServiceProviderLocationId function, and you might set selected value in state, you need to write that in value prop above so that it will become a controlled component.

Demo

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
-1

I think you need to brush up html element basics here. So to select value in dropdown by default you need to add selected to html tag and that should take care of default selected item.

So you need to add login to select the element in the option and while change you should be able to get default value

let serviceProviderLocationNames = this.props.serviceProviderLocationName.map((location, key) => {
  return <option 
    key={key} 
    value={location.SERVICE_PROVIDER_LOCATION_ID} 
    selected={key=== PUT_INDEX_TO_BE_DEFAULT_SELECTED}
  >
    {location.DESCRIPTION}
  </option>
});
Anil Namde
  • 6,452
  • 11
  • 63
  • 100