react-data-grid icon indicating copy to clipboard operation
react-data-grid copied to clipboard

Sorting and filtering at the same time

Open Zladivliba opened this issue 6 years ago • 2 comments

Hello,

I'm trying to find an example with both filtering AND sorting at the same time, is there an example somewhere we could use ?

Thanks (I've been spending my entire day on this with no results unfortunately)

Zladivliba avatar Apr 17 '20 18:04 Zladivliba

I made something like this: (works for version 6.0.1, don't know about others) live demo: https://codesandbox.io/s/rdg-column-sorting-and-filtering-fc6ep?file=/src/index.js This is the non-basic example with sort, filter and select rows Hope this helps.

import React from "react";
import ReactDOM from "react-dom";
import ReactDataGrid from "react-data-grid";
import { Toolbar, Data } from "react-data-grid-addons";

const selectors = Data.Selectors;

const heightOfRow = 40;
const heightOfHeaderRow = 40;

const defaultColumnProperties = {
  sortable: true,
  filterable: true,
  editable: true,
  width: 200
};

const initialColumns = [
  { key: "id", name: "ID" },
  { key: "title", name: "Title" },
  { key: "realColumn", name: "Column with real values", type: "real" }
].map(c => ({ ...c, ...defaultColumnProperties }));

const initialRows = [
  { id: 0, title: "Task 11", realColumn: 100.10 },
  { id: 1, title: "Some text 11", realColumn: 101 },
  { id: 2, title: "Idk 22", realColumn: 1000.01 },
  { id: 3, title: "AAA 22", realColumn: 11 },
  { id: 4, title: "bbb 22", realColumn: 99.123 },
  { id: 5, title: "ccc 3", realColumn: 1001.01 },
  { id: 6, title: "dddd 4", realColumn: 60.11 },
];

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      columns: initialColumns,
      rows: initialRows,
      filters: {},
      selectedRows: [], //for row selection (column with checkboxes)
    };
  }

  onGridSort = (sortColumn, sortDirection) => {
    const tmpCol = this.state.columns.find(col => col.key === sortColumn);
    let numberSorting = false;
    if (tmpCol.type === "integer" || tmpCol.type === "real")
      numberSorting = true; //default sorting is comparing strings, here we need number-sorting

    const comparer = (a, b) => {
      if (sortDirection === "ASC") {
        if (numberSorting) {
          return a[sortColumn] - b[sortColumn];
        }
        return a[sortColumn] > b[sortColumn] ? 1 : -1;
      } else if (sortDirection === "DESC") {
        if (numberSorting) {
          return b[sortColumn] - a[sortColumn];
        }
        return a[sortColumn] < b[sortColumn] ? 1 : -1;
      } else {
        return a.id > b.id ? 1 : -1; //restore to sorting by id
      }
    };

    this.setState(prevState => ({
        rows: [...prevState.rows].sort(comparer)
    }))

  };

  getColumns() {
    return this.state.columns;
  }

  getRows(rows, filters) {
    return selectors.getRows({ rows, filters });
  }

  filteredRows = () => {
    return this.getRows(this.state.rows, this.state.filters);
  };

  handleFilterChange = filter => {
    this.setState(prevState => {
      const newFilters = { ...prevState.filters };
      if (filter.filterTerm) {
        newFilters[filter.column.key] = filter;
      } else {
        delete newFilters[filter.column.key];
      }
      return {
        filters: newFilters,
        selectedRows: [] //clear selected (checkboxes column) rows when filtering
      };
    });
  };

  onClearFilters = () => {
    this.setState({
      filters: {},
      selectedRows: [] //if you have column with checkboxes then clear them all
    });
  };

  // Needed to have selected row even when sorting (select)
  onRowsSelected = (rows) => {
      this.setState( (prevState) => ({ 
          selectedRows: prevState.selectedRows.concat(rows.map(r => r.row.id)) //assuming id is the key of each row
      }));
  };
  // Needed to have selected row even when sorting (deselect)
    onRowsDeselected = (rows) => {
        let rowIndexes = rows.map(r => r.row.id); //assuming id is the key of each row
        
        this.setState( prevState => ({
            selectedRows: prevState.selectedRows.filter(
                i => rowIndexes.indexOf(i) === -1
            )
        }));
    };
  

  //Also onGridRowsUpdated should update only filtered rows:
    onGridRowsUpdated = ({ fromRow, toRow, updated }) => {
    this.setState(prevState => {
      const rows = prevState.rows;
      const filtered = this.filteredRows();
      for (let i = fromRow; i <= toRow; i++) {
        const rows_index = rows.map( x => x.id ).indexOf(filtered[i].id); //assuming "id" is the key of each row
        rows[rows_index] = { ...filtered[i], ...updated };
      }
      
      return {
        rows: rows,
      }
    });

  }

  render() {
    return (
      <ReactDataGrid
        onGridRowsUpdated={this.onGridRowsUpdated}
        columns={this.getColumns()}
        rowGetter={i => this.filteredRows()[i]}
        rowsCount={this.filteredRows().length}
        onGridSort={this.onGridSort}
        onAddFilter={this.handleFilterChange}
        onClearFilters={this.onClearFilters}
        
        toolbar={<Toolbar enableFilter={true} />}
        
        enableCellSelect={true}
        
        //for column with checkboxes 
        rowSelection={{
            showCheckbox: true,
            onRowsSelected: this.onRowsSelected,
            onRowsDeselected: this.onRowsDeselected,
            selectBy: {
                keys: {
                    rowKey: "id",
                    values: this.state.selectedRows
                }
            }
        }}

        minHeight={400}
        headerRowHeight={heightOfHeaderRow}
        rowHeight={heightOfRow}
        />
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<Example />, rootElement);

emsi-iggy avatar Apr 20 '20 20:04 emsi-iggy

You can check the examples for v7 canary. It should be straightforward to add both

https://github.com/adazzle/react-data-grid/blob/canary/stories/demos/HeaderFilters.tsx https://github.com/adazzle/react-data-grid/blob/canary/stories/demos/CommonFeatures.tsx

Website https://adazzle.github.io/react-data-grid/canary/?path=/story/demos--common-features

Changelog https://github.com/adazzle/react-data-grid/blob/canary/CHANGELOG.md

amanmahajan7 avatar Apr 29 '20 14:04 amanmahajan7