Reputation: 1991
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
Upvotes: 3
Views: 19357
Reputation: 4165
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;
Upvotes: 3
Reputation: 256
In the Dropdown component you can do something like this
{(this.props.options.length > 1) ? <option>{this.props.placeholder}</option>: null}
Browser will automatically select the first option in the list.
Upvotes: 0