Мне нужно выбрать несколько элементов с реакцией js.
- Выбранная опция должна быть видна в другом div.
- Может быть возможность удалить выбранную опцию и вернуть ее в список опций.
class App extends Component {
constructor(props) {
super(props);
this.state = {
dropdown: ["BMW", "AUDI", "MARUTI", "JAGUAR", "FERRARI", "SWIFT", "DUSTER"],
selected: [],
default: "Select option"
};
}
componentDidMount(){
let {dropdown,selected} = this.state
dropdown = dropdown.filter(val => !selected.includes(val));
this.setState({dropdown})
}
handleSelect = (e) => {
this.setState({ selected: [...this.state.selected, e.target.value] })
var selectobject = document.getElementById("mySelect");
for (var i = 0; i < selectobject.length; i++) {
if (selectobject.options[i].value == e.target.value)
selectobject.remove(i);
}
var x = document.getElementById("mySelect").length;
if (x === 1) {
this.setState({
default: "No more options"
})
}
}
handleRemove = (item) => {
this.setState({ dropdown: [...this.state.dropdown, item] })
const deletedItem = this.state.selected.filter(data => data !== item)
this.setState({ selected: deletedItem }, () => {
var x = document.getElementById("mySelect").length;
if (x > 1) {
this.setState({
default: "Select option"
})
}
})
}
render() {
return (
<>
<div className="container">
<div className="row">
<div className="col-8 my-5">
<div className=" d-flex">
{
this.state.selected && this.state.selected.map((item, key) => {
return (
<div className="my-3 mx-2" key={key}>
<button type="button" class="btn btn-primary">
{item} <span class="badge badge-light" onClick={() => this.handleRemove(item)}>X</span>
</button>
</div>
)
})
}
</div>
<select onChange={this.handleSelect} className="w-100" id="mySelect">
<option value="">{this.state.default}</option>
{
this.state.dropdown && this.state.dropdown.map((data, key) => {
return (
<option value={data} key={key}>{data}</option>
)
})
}
</select>
</div>
</div>
</div>
</>
);
}
}