Reputation: 1499
I have developed the dropdown selection for the single selection. Now i want to make it as multiple selection. How can i pass the multiple ids in the API response. ?
My working code for single selection is like this:
class Xyz extends React.Component {
constructor(props) {
super(props);
this.state = {id: props.defaultValue.id, name: props.defaultValue.name, open: true};
}
updateData = () => {
console.log(this.state.id)
this.props.onUpdate({id: this.state.id, name: this.state.name});
api.request({url: `/api-route/${this.props.id}`, method: 'put', data: {[this.field]: this.state.id} })
.then(res => (`${this.field} have been updated`)
.catch(er => console.log(er));
}
render() {
return (
<React.Fragment>
<select
multiple={true}
defaultValue={[this.props.defaultValue.id]}
onChange={ev => this.setState({ id: ev.target.value, name: ev.nativeEvent.target[ev.nativeEvent.target.selectedIndex].text })}>
{this.props[this.field].map((name, index) => <option key={index} value={index}>{name}</option>)}
</select>
<button type='button' className='btn btn-primary' onClick={this.updateData}>Save</button>
</React.Fragment>
);
}
}
Upvotes: 1
Views: 969
Reputation: 3589
For Multiple selections, you can try the below plugin
https://github.com/JedWatson/react-select
const options = [];
class App extends React.Component {
state = {
selectedOption: null,
}
constructor(props) {
super(props);
this.props[this.field].map((name, index) => {
options.push({ value: index, label: name });
});
}
handleChange = (selectedOption) => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
}
render() {
const { selectedOption } = this.state;
return (
<Select
value={selectedOption}
onChange={this.handleChange}
options={options}
isMulti
/>
);
}
}
To know more about react-select check the below post
https://medium.com/@nidhinkumar/react-select-852e90d549df
Upvotes: 1