Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically set value of a React Dropdown

I have this code

<Dropdown
    id="city"
    placeholder="Select a city"
    options={this.state.cities}
    onChange={this.onChangeHandler}
    />;

this will display a dropdown showing the placeholder "Select a city".

What I am trying to do is, if this.state.cities only has one element, to set it as preselected. Otherwise keep showing the placeholder text and all the options underneath.

the library I am using is https://www.npmjs.com/package/react-dropdown

thanks

like image 657
user3174311 Avatar asked Jun 22 '26 17:06

user3174311


1 Answers

According to the documentation, the Dropdown component takes a value prop.

import Dropdown from 'react-dropdown'
import 'react-dropdown/style.css'

class App extends React.Component {
   constructor() {
     super();
      this.state={
        cities: ["New York", "San Francisco", "Seattle", "Washington DC"],
        selectedCity: ""
      }
   }

   handleSelectCity = (option)=> {
      const selectedCity = option.value
      this.setState({selectedCity});
   }

   render() {
      const {selectedCity, cities} = this.state;

      return (
        <Dropdown 
          options={cities} 
          onChange={this.handleSelectCity} 
          value={selectedCity} 
          placeholder="Select an option" 
        />
      )
   }
}

export default App;
like image 156
lomse Avatar answered Jun 24 '26 07:06

lomse



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!