最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Material Table Get and Set Filter Values - Stack Overflow

programmeradmin1浏览0评论

How can I get and set the filter values programmatically using material-table?

I want users to be able to save filter configurations as reports and recall them as needed.

How can I get and set the filter values programmatically using material-table?

I want users to be able to save filter configurations as reports and recall them as needed.

Share Improve this question asked Sep 10, 2020 at 2:04 Alex MckayAlex Mckay 3,70619 silver badges31 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Get works with a hook on change:

onFilterChange={(filters) => {
  console.log('onFilterChange', filters);
}}

result is an array of filter definitions per column, looks like:

[
// [...]
  {
    "column": {
      "title": "Date",
      "field": "file_date",
      "type": "date",
      "tableData": {
        "columnOrder": 3,
        "filterValue": "2020-11-10T15:20:00.000Z",
        "groupSort": "asc",
        "width": "...", // lots of css calc stuff... :(
        "additionalWidth": 0,
        "id": 4
      }
    },
    "operator": "=",
    "value": "checked"
  }
]

setting the filter on mount could/should work with defaultFilter at each column definition.

There are two parts to this, the get and the set.

  • Get - handled through the use of the tableRef prop on the MaterialTable ponent
  • Set - handled through the defaultFilter value on a column object.
import MaterialTable from "material-table";
import React, { useRef } from "react";
import { tableIcons } from "./tableIcons";

const firstNameFilter = 'Neil'

function App() {
  const tableRef = useRef<any>();
  return (
    <div>
      <button onClick={saveFilters(tableRef)}>Filters</button> // GET OCCURS HERE
      <MaterialTable
        tableRef={tableRef}
        icons={tableIcons}
        columns={[
          { title: "First", field: "name", defaultFilter: firstNameFilter }, // SET OCCURS HERE
          { title: "Last", field: "surname" }
        ]}
        data={[
          { name: "Neil", surname: "Armstrong" },
          { name: "Lance", surname: "Armstrong" },
          { name: "Bob", surname: "Hope" }
        ]}
        options={{ filtering: true }}
        title="Reports"
      />
    </div>
  );
}

function saveFilters(tableRef: React.MutableRefObject<any>) {
  return function handler() {
    const columns = tableRef?.current?.state.columns.map((column: any) => ({
      field: column.field,
      filterValue: column.tableData.filterValue
    }));
    console.log(JSON.stringify(columns, null, 2));
  };
}

export { App };
发布评论

评论列表(0)

  1. 暂无评论