htmlcssreactjsadvanced-filterreact-functional-component

How to build a advanced filter component in react?


I don't seem to find quite exactly what I am looking for despite many research. I'm building a real estate react app, in the search page I want to be able to filter result based on price range, bedroom count, bathroom count, house type. I went over some tutorial, but I'm not quite sure if they point me in the right direction. I want to use functional component, react hooks, no redux or MobX and no css framework. Is it a necessity to use a </form> tag? How can we dynamically apply multiple filter on an array? Because the filter will work on local data that has been downloaded from an api stored in an array. I would like as much as explanation as possible please. Here's an example: enter image description here


Solution

  • You are getting data from API and supplying it to you component. Now, this filter component has a local copy of the data, which will be used to filter. I can't comment on how you will create filters in your component (from UI point of view). I can suggest to use lodash library to apply various filters at once on an array of objects. One of the examples I can think of is -

    var location = 'Miami, FL'
    var priceFrom = $2000;
    var priceTo = $3000;
    
    var filterFunctions = _.overEvery([locationFilter, priceFilter]);
    
    locationFilter(data) {
      return data.filter(o => o.location === location);
    }
    
    priceFilter(data) {
      return data.filter(o => o.price >= priceFrom && o.price <= priceTo);
    }
    
    var result = yourData.filter(filterFunctions);
    

    To check the status of what filters are selected by user, you need to maintain it in local state of component. I guess, the best way to declare it as an object array. Push the filter and it's value when changed/selected by user. Remove it from array if user un-select it back. For example if user selects something from location drop down, push the value in the array, if not already there. Update the value otherwise based on name. The array should look this below (assuming react component):

    this.state.filters = [{name: 'price', value: 2000},
       {name: 'location', value: 'Miami, FL'}];
    
    

    Now use this array to decide what filter functions you want to apply:

    locationFilter(location) {
      return this.state.yourData.filter(o => o.location === location);
    }
    
    
    var result;
    filters.map(f => {
      switch(f.name) {
        case 'location':
          result = locationFilter(f.value);
          break;
        case 'price':
          result = priceFilter(f.value);
          break;
      }
      // result contains filtered result
    });