I'm using the react-select select box to allow the user to select multiple options from a dropdown menu. I was wondering if it's possible to preselect a few options (already have the selectbox populated). I've created a sandbox for the project:
https://codesandbox.io/s/blissful-almeida-4iux6
This is the dashboard that calls the SelectBox, in the state I have the "preselectedOptions" which are the options I would like already selected. In this example I would like to have "Option 1" and "Option 3" already selected:
import React, { Component } from "react";
import SelectBox from "./dropdown";
class Dashboard extends Component {
constructor() {
super();
this.state = {
currentOptions: [],
preselectedOptions: ["Option 1", "Option 3"]
};
}
updateOptions(selected) {
this.setState({
currentOptions: selected
});
}
showSelected() {
alert(this.state.currentOptions.length + " selected");
}
render() {
return (
<div>
<SelectBox selectedOptions={this.updateOptions.bind(this)} />
<br />
<button onClick={() => this.showSelected()}>Selected</button>
</div>
);
}
}
export default Dashboard;
And here is the SelectBox:
import React, { Component } from "react";
import Select from "react-select";
class SelectBox extends Component {
constructor(props) {
super(props);
this.customStyles = {
input: styles => {
return {
...styles,
height: "45px"
};
}
};
this.handleChange = this.handleChange.bind(this);
this.options = [];
this.options.push({ value: "Option 1", label: "Option 1" });
this.options.push({ value: "Option 2", label: "Option 2" });
this.options.push({ value: "Option 3", label: "Option 3" });
this.options.push({ value: "Option 4", label: "Option 4" });
this.options.push({ value: "Option 5", label: "Option 5" });
}
handleChange(e) {
this.props.selectedOptions(e);
}
render() {
return (
<div>
<Select
isMulti
maxMenuHeight="150px"
styles={this.customStyles}
options={this.options}
onChange={this.handleChange}
className="basic-multi-select"
classNamePrefix="select"
/>
</div>
);
}
}
export default SelectBox;
Thanks!