Search code examples
reactjsdatatablefiltering

Data Table filtering using react-data-table-component


I need to convert the below code to normal class component without hooks, can anyone help me with this, here is the link which i am referring to https://jbetancur.github.io/react-data-table-component/?path=/story/filtering--example-1 I need to do filtering without using hooks as i am using only class component. Below are the versions I am using:- "react-data-table-component": "^6.9.3", "react": "^16.12.0",


Solution

  • I think This is what you are looking for...

     class BasicTable extends React.PureComponent {
          constructor(props) {
            super(props);
            this.state = { filterText: "", resetPaginationToggle: false };
            this.filteredItems = fakeUsers.filter(
              (item) =>
                item.name && item.name.toLowerCase().includes(filterText.toLowerCase())
            );
          }
    
          handleClear = () => {
            const { resetPaginationToggle, filterText } = this.state;
    
            if (this.state.filterText) {
              this.setState({
                resetPaginationToggle: !resetPaginationToggle,
                filterText: ""
              });
            }
          };
    
          getSubHeaderComponent = () => {
            return (
              <FilterComponent
                onFilter={(e) => {
                  let newFilterText = e.target.value;
                  this.filteredItems = fakeUsers.filter(
                    (item) =>
                      item.name &&
                      item.name.toLowerCase().includes(newFilterText.toLowerCase())
                  );
                  this.setState({ filterText: newFilterText });
                }}
                onClear={this.handleClear}
                filterText={this.state.filterText}
              />
            );
          };
    
          render() {
            return (
              <DataTable
                title="Contact List"
                columns={columns}
                data={this.filteredItems}
                pagination
                paginationResetDefaultPage={this.state.resetPaginationToggle} // optionally, a hook to reset pagination to page 1
                subHeader
                subHeaderComponent={this.getSubHeaderComponent()}
                selectableRows
                persistTableHead
              />
            );
          }
        }