Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React multiple filter dropdowns

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});
}
like image 639
cocoa Avatar asked Dec 11 '22 20:12

cocoa


1 Answers

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!

like image 72
foxdonut Avatar answered Dec 25 '22 16:12

foxdonut