How do I create select filters for my material-ui table in a reusable way?

Viewed 16597

I am creating my own filterable table in React using Material UI.

I created a table which I pass the following props:

      createObject('BlueTree','05-02-2015','ativo', 'Vinhedo', 'São Paulo'),
      createObject('Inner','07-08-2016','inativo', 'Belo Horizonte', 'Minas Gerais'),
      createObject('Teste','05-02-2017','ativo', 'Teresina', 'Piauí'),
      createObject('hello','05-02-2015','ativo', 'Osasco', 'São Paulo'),
      createObject('Inner','07-08-2016','inativo', 'Lavras', 'Minas Gerais'),
      createObject('Teste','05-02-2017','inativo', 'Barras', 'Piauí'),
      createObject('xiaomi','05-02-2015','inativo', 'Indaiatuba', 'São Paulo'),
      createObject('Inner','07-08-2016','ativo', 'Pedrinhas', 'Minas Gerais'),
      createObject('Teste','05-02-2017','ativo', 'Esperantina', 'Piauí'), 

and select tag such as "State, City..."

selectFilter: [
      { Name: 'estado'},
      { Name: 'cidade'},
      { Name: 'status'},
      { Name: 'pms'},
    ],

And this is where I call the table

<Table listHotels={listHotels} selectFilter={selectFilter}></Table>

Inside Table component I am able to create material UI selects that will represent the data.

However, I am not sure how to filter these arrays based on the select option since, if I have 4 select tags filters I would have to filter the array based on the option selected. And the logic would change if I add one more selects to it, and that's not reusable at all.

Is this really a front-end task or should I leave it with the back end? In my opinion it makes more sense to just execute a select on a table on the back end and return the filtered data.

1 Answers

You can go either way; what you want is a displayed set. For each item check if it meets the criteria and then add it to the displayed:

handleFilterSelected = () => {
  const filters = {
    location: "Whatever",
    priceMin: 0.0,
    priceMax: 100.0
  };
  this.setState({
    filters: filters,
    filteredItems: this.props.items.filter((item) => {
      return item.location === filters.location
        && item.price >= filters.priceMin
        && item.price <= filters.priceMax;
    })
  });
}

render() {
  return (
    <Table>
      <TableBody>
        {this.state.filteredItems.map((item) =>
          <TableRow>
            <TableCell>{item.location}</TableCell>
            <TableCell>{item.price}</TableCell>
          </TableRow>
        )}
      </TableRow>
    </Table>
  );
}

If you have more than a few hundred items, you will probably want to do this on the backend. So your component will be adjusting HTTP URL query parameters that are sent rather than modifying the displayed list of items.

Related