I have React app where you can filter a list based off a few different properties. Currently I am able to filter each category one at a time, but I'd like to filter multiple categories at once, so the list would keep getting smaller as you select more filters. Then when you clear out all the values it would go back to the original list. How can I achieve this?
demo
Sample of my code
getInitialState: function() {
return {
data: this.props.data,
bender: '',
nation: '',
person: '',
show: ''
}
},
filterItems: function(val, type) {
switch (type) {
case 'bender':
this.setState({bender: val});
break;
case 'nation':
this.setState({nation: val});
break;
case 'person':
this.setState({person: val});
break;
case 'show':
this.setState({show: val});
break;
default:
break;
}
var filteredItems;
if (val) {
filteredItems = this.props.data.filter(function(item) {
return item[type] === val;
});
} else {
filteredItems = this.props.data;
}
this.setState({data: filteredItems});
}
Your code is filtering by just one criteria at a time. You need to loop over the four criteria and accumulate the filtering:
["bender", "nation", "person", "show"].forEach(function(filterBy) {
var filterValue = state[filterBy];
if (filterValue) {
filteredItems = filteredItems.filter(function(item) {
return item[filterBy] === filterValue;
});
}
});
Full code:
http://codepen.io/foxdonut/pen/GpwRJB?editors=001
I hope that is helpful!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With