Kalyan A
Kalyan A

Reputation: 301

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",

Upvotes: 4

Views: 23889

Answers (2)

Akash Amar
Akash Amar

Reputation: 441

You can filter in the component itself

<DataTable
    pagination="true"
    columns={columns}
    data={leaderBoardList.filter((item) => {
      if (searchTerm === "") {
        return item;
      } else if (
        item.name.toLowerCase().includes(searchTerm.toLowerCase())
      ) {
        return item;
      }
    })}
  />

Upvotes: 10

Harsh kurra
Harsh kurra

Reputation: 1216

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
          />
        );
      }
    }

Upvotes: 3

Related Questions