Reputation: 1942
I have a multiselect developed with ant Design which his values is fetched from the backend :
"jours": [
{
"id": 1,
"jour": "Lundi"
},
{
"id": 2,
"jour": "Mardi"
},
{
"id": 3,
"jour": "Mercredi"
},
{
"id": 4,
"jour": "Jeudi"
},
{
"id": 5,
"jour": "Vendredi"
},
{
"id": 6,
"jour": "Samedi"
}
]
My code is :
jour:[], jours:[], joursId:[],
handleJourChange = (jour) => {
this.state.jours.map((jourId)=>{
this.state.joursId.push(""+jourId.id+"");
this.setState({
joursId: this.state.joursId
})
console.log(this.state.joursId)
if (jour.includes('all')) {
this.setState({ jour: this.state.joursId });
}
else {
this.setState({jour :jour});
}
})
}
<Select id="motif" name= "motif" mode="multiple" showArrow allowClear showSearch style={{ width: '535px' }} placeholder="Sélectionnez le(s) motif(s)" value={this.state.jour} onChange={this.handleJourChange}
optionFilterProp="children" filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
<Option value="all">Sélectionner tout</Option>
{ this.state.id_user > 0 && this.state.jours.map((jour)=>
<Option key={jour.id} value={jour.id}>{jour.jour}</Option>
)}
</Select>
My codeSandbox: https://codesandbox.io/s/async-meadow-2clz5
When I run it :
The option of select is the id not the values of the data.
When I click on select all, all values will be selected and I clear it, it will be cleared, but when I reselect all, it will be selected all multiple times, which I can't cleared it.
How can I fix it ?
Upvotes: 0
Views: 2368
Reputation: 19224
This can be implemented by changing the handleChange
functionality to:
handleJourChange = jour => {
if (jour.includes("all")) {
this.setState(prevState => ({
jour: prevState.jours.map(item => item.id)
}));
} else {
this.setState({
jour
});
}
};
There is some extra code involving joursId
in your codesandbox that I'm not sure of.
Full CodeSandbox
Upvotes: 1