@7itec/mui-datatables 中文文档教程

发布于 4年前 浏览 30 项目主页 更新于 3年前

MUI-Datatables - Datatables for Material-UI

构建状态NPM 下载覆盖状态npm 版本

MUI-Datatables 是一个基于 Material-UI 的响应式数据表组件。 它具有过滤、可调整大小的列、查看/隐藏列等功能, 可拖动列、搜索、导出为 CSV 下载、打印、可选行、可扩展行、分页和排序。 除了在大多数视图上自定义样式的能力之外,移动/平板设备还提供三种响应模式“垂直”、“标准”和“简单”。

版本 3 已经发布! 您可以在此处阅读更新

Table of contents

Install

npm install mui-datatables --save

如果您的项目尚未使用它们,则需要安装 @material-ui/core@material-ui /icons 还有。

Demo

Edit react-to-print

在这里

Usage

对于一个简单的表格:

import MUIDataTable from "mui-datatables";

const columns = ["Name", "Company", "City", "State"];

const data = [
 ["Joe James", "Test Corp", "Yonkers", "NY"],
 ["John Walsh", "Test Corp", "Hartford", "CT"],
 ["Bob Herm", "Test Corp", "Tampa", "FL"],
 ["James Houston", "Test Corp", "Dallas", "TX"],
];

const options = {
  filterType: 'checkbox',
};

<MUIDataTable
  title={"Employee List"}
  data={data}
  columns={columns}
  options={options}
/>

或自定义列:

import MUIDataTable from "mui-datatables";

const columns = [
 {
  name: "name",
  label: "Name",
  options: {
   filter: true,
   sort: true,
  }
 },
 {
  name: "company",
  label: "Company",
  options: {
   filter: true,
   sort: false,
  }
 },
 {
  name: "city",
  label: "City",
  options: {
   filter: true,
   sort: false,
  }
 },
 {
  name: "state",
  label: "State",
  options: {
   filter: true,
   sort: false,
  }
 },
];

const data = [
 { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
 { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
 { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
 { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
];

const options = {
  filterType: 'checkbox',
};

<MUIDataTable
  title={"Employee List"}
  data={data}
  columns={columns}
  options={options}
/>

API

<MUIDataTable />

该组件接受以下道具:

NameTypeDescription
titlearrayTitle used to caption table
columnsarrayColumns used to describe table. Must be either an array of simple strings or objects describing a column
dataarrayData used to describe table. Must be either an array containing objects of key/value pairs with values that are strings or numbers, or arrays of strings or numbers (Ex: data: [{"Name": "Joe", "Job Title": "Plumber", "Age": 30}, {"Name": "Jane", "Job Title": "Electrician", "Age": 45}] or data: [["Joe", "Plumber", 30], ["Jane", "Electrician", 45]]). The customBodyRender and customBodyRenderLite options can be used to control the data diaplay.
optionsobjectOptions used to describe table
componentsobjectCustom components used to render the table

Options:

NameTypeDefaultDescription
caseSensitivebooleanfalseEnable/disable case sensitivity for search.
confirmFiltersbooleanfalseWorks in conjunction with the customFilterDialogFooter option and makes it so filters have to be confirmed before being applied to the table. When this option is true, the customFilterDialogFooter callback will receive an applyFilters function which, when called, will apply the filters to the table. Example
columnOrderarrayAn array of numbers (column indices) indicating the order the columns should be displayed in. Defaults to the order provided by the Columns prop. This option is useful if you'd like certain columns to swap positions (see draggableColumns option).
countnumberUser provided override for total number of rows.
customFilterDialogFooterfunctionAdd a custom footer to the filter dialog. customFilterDialogFooter(curentFilterList: array, applyFilters: function) => React Component
customFooterfunctionRender a custom table footer. function(count, page, rowsPerPage, changeRowsPerPage, changePage,textLabels: object) => string|React Component Example
customRowRenderfunctionOverride default row rendering with custom function. customRowRender(data, dataIndex, rowIndex) => React Component
customSearchfunctionOverride default search with custom function. customSearch(searchQuery: string, currentRow: array, columns: array) => boolean
customSearchRenderfunctionRender a custom table search. customSearchRender(searchText: string, handleSearch, hideSearch, options) => React Component
customSortfunctionOverride default sorting with custom function. If you just need to override the sorting for a particular column, see the sortCompare method in the column options. function(data: array, colIndex: number, order: string) => array Example
customTableBodyFooterRenderfunctionRender a footer under the table body but above the table's standard footer. This is useful for creating footers for individual columns. Example
customToolbarfunctionRender a custom toolbar
customToolbarSelectfunctionRender a custom selected rows toolbar. function(selectedRows, displayData, setSelectedRows) => void
downloadbooleantrueShow/hide download icon from toolbar
downloadOptionsobjectsee ->An object of options to change the output of the CSV file:

  • filename: string
  • separator: string
  • filterOptions: object
    • useDisplayedColumnsOnly: boolean
    • useDisplayedRowsOnly: boolean

默认值:{filename: 'tableDownload.csv', separator: ','}

draggableColumnsobject{}An object of options describing how dragging columns should work. The options are:

  • enabled:boolean: Indicates if draggable columns are enabled. Defaults to false.
  • transitionTime:number: The time in milliseconds it takes for columns to swap positions. Defaults to 300.

To disable the dragging of a particular column, see the "draggable" option in the columns options. Dragging a column to a new position updates the columnOrder array and triggers the onColumnOrderChange callback.
elevationnumber4Shadow depth applied to Paper component.
enableNestedDataAccessstring""If provided a non-empty string (ex: "."), it will use that value in the column's names to access nested data. For example, given a enableNestedDataAccess value of "." and a column name of "phone.cell", the column would use the value found in phone:{cell:"555-5555"}. Any amount of nesting will work. Example demonstrates the functionality.
expandableRowsbooleanfalseEnable/disable expandable rows. Example
expandableRowsHeaderbooleantrueShow/hide the expand all/collapse all row header for expandable rows.
expandableRowsOnClickbooleanfalseEnable/disable expand trigger when row is clicked. When False, only expand icon will trigger this action.
filterbooleantrueShow/hide filter icon from toolbar.
filterTypestringChoice of filtering view. enum('checkbox', 'dropdown', 'multiselect', 'textField', 'custom')
fixedHeaderbooleantrueEnable/disable a fixed header for the table Example
fixedSelectColumnbooleantrueEnable/disable fixed select column. Example
isRowExpandablefunctionEnable/disable expansion or collapse on certain expandable rows with custom function. Will be considered true if not provided. function(dataIndex: number, expandedRows: object(lookup: {dataIndex: number}, data: arrayOfObjects: {index: number, dataIndex: number})) => boolean.
isRowSelectablefunctionEnable/disable selection on certain rows with custom function. Returns true if not provided. function(dataIndex: number, selectedRows: object(lookup: {dataindex: boolean}, data: arrayOfObjects: {index, dataIndex})) => boolean.
jumpToPagebooleanfalseWhen true, this option adds a dropdown to the table's footer that allows a user to navigate to a specific page. Example
onCellClickfunctionCallback function that triggers when a cell is clicked. function(colData: any, cellMeta: { colIndex: number, rowIndex: number, dataIndex: number }) => void
onChangePagefunctionCallback function that triggers when a page has changed. function(currentPage: number) => void
onChangeRowsPerPagefunctionCallback function that triggers when the number of rows per page has changed. function(numberOfRows: number) => void
onColumnOrderChangefunctionCallback function that triggers when a column has been dragged to a new location. function(newColumnOrder:array, columnIndex:number, newPosition:number) => void
onColumnSortChangefunctionCallback function that triggers when a column has been sorted. function(changedColumn: string, direction: string) => void
onDownloadfunctionA callback function that triggers when the user downloads the CSV file. In the callback, you can control what is written to the CSV file. This method can be used to add the Excel specific BOM character (see this example). function(buildHead: (columns) => string, buildBody: (data) => string, columns, data) => string. Return false to cancel download of file.
onFilterChangefunctionCallback function that triggers when filters have changed. function(changedColumn: string, filterList: array, type: enum('checkbox', 'dropdown', 'multiselect', 'textField', 'custom', 'chip', 'reset'), changedColumnIndex, displayData) => void
onFilterChipClosefunctionCallback function that is triggered when a user clicks the "X" on a filter chip. function(index : number, removedFilter : string, filterList : array) => void Example
onFilterConfirmfunctionCallback function that is triggered when a user presses the "confirm" button on the filter popover. This occurs only if you've set confirmFilters option to true. function(filterList: array) => void Example
onFilterDialogClosefunctionCallback function that triggers when the filter dialog closes. function() => void
onFilterDialogOpenfunctionCallback function that triggers when the filter dialog opens. function() => void
onRowClickfunctionCallback function that triggers when a row is clicked. function(rowData: string[], rowMeta: { dataIndex: number, rowIndex: number }) => void
onRowExpansionChangefunctionCallback function that triggers when row(s) are expanded/collapsed. function(currentRowsExpanded: array, allRowsExpanded: array, rowsExpanded: array) => void
onRowsDeletefunctionCallback function that triggers when row(s) are deleted. function(rowsDeleted: object(lookup: {[dataIndex]: boolean}, data: arrayOfObjects: {index: number, dataIndex: number}), newTableData) => void OR false (Returning false prevents row deletion.)
onRowSelectionChangefunctionCallback function that triggers when row(s) are selected/deselected. function(currentRowsSelected: array, allRowsSelected: array, rowsSelected: array) => void
onSearchChangefunctionCallback function that triggers when the search text value has changed. function(searchText: string) => void
onSearchClosefunctionCallback function that triggers when the searchbox closes. function() => void
onSearchOpenfunctionCallback function that triggers when the searchbox opens. function() => void
onTableChangefunctionCallback function that triggers when table state has changed. function(action: string, tableState: object) => void
onTableInitfunctionCallback function that triggers when table state has been initialized. function(action: string, tableState: object) => void
onViewColumnsChangefunctionCallback function that triggers when a column view has been changed. Previously known as onColumnViewChange. function(changedColumn: string, action: string) => void
pagenumberUser provided page for pagination.
paginationbooleantrueEnable/disable pagination.
printbooleantrueShow/hide print icon from toolbar.
renderExpandableRowfunctionRender expandable row. function(rowData, rowMeta) => React Component Example
resizableColumnsbooleanfalseEnable/disable resizable columns.
responsivestring'stacked'Enable/disable responsive table views. Options:

  • "vertical" (default value): In smaller views the table cells will collapse such that the heading is to the left of the cell value.
  • "standard": Table will stay in the standard mode but make small changes to better fit the allocated space.
  • "simple": On very small devices the table rows will collapse into simple display.

Example
rowHoverbooleantrueEnable/disable hover style over rows.
rowsExpandedarrayUser provided expanded rows.
rowsPerPagenumber10Number of rows allowed per page.
rowsPerPageOptionsarray[10,15,100]Options to provide in pagination for number of rows a user can select.
rowsSelectedarrayUser provided array of numbers (dataIndexes) which indicates the selected rows.
searchbooleantrueShow/hide search icon from toolbar.
searchPlaceholderstringSearch text placeholder. Example
searchPropsobject{}Props applied to the search text box. You can set method callbacks like onBlur, onKeyUp, etc, this way. Example
searchOpenbooleanfalseInitially displays search bar.
searchTextstringSearch text for the table.
selectableRowsstring'multiple'Indicates if rows can be selected. Options are "multiple", "single", "none".
selectableRowsHeaderbooleantrueShow/hide the select all/deselect all checkbox header for selectable rows.
selectableRowsHideCheckboxesbooleanfalseHides the checkboxes that appear when selectableRows is set to "multiple" or "single". Can provide a more custom UX, especially when paired with selectableRowsOnClick.
selectableRowsOnClickbooleanfalseEnable/disable select toggle when row is clicked. When False, only checkbox will trigger this action.
selectToolbarPlacementstring'replace'Controls the visibility of the Select Toolbar, options are 'replace' (select toolbar replaces default toolbar when a row is selected), 'above' (select toolbar will appear above default toolbar when a row is selected) and 'none' (select toolbar will never appear)
serverSidebooleanfalseEnable remote data source.
setFilterChipPropsfunctionIs called for each filter chip and allows you to place custom props on a filter chip. function(colIndex: number, colName: string, filterValue: string) => object Example
setRowPropsfunctionIs called for each row and allows you to return custom props for this row based on its data. function(row: array, dataIndex: number, rowIndex: number) => object Example
setTablePropsfunctionIs called for the table and allows you to return custom props for the table based on its data. function() => object Example
sortbooleantrueEnable/disable sort on all columns.
sortFilterListbooleantrueEnable/disable alphanumeric sorting of filter lists.
sortOrderobject{}Sets the column to sort by and its sort direction. To remove/reset sorting, input in an empty object. The object options are the column name and the direction: name: string, direction: enum('asc', 'desc') Example
tableIdstringauto generatedA string that is used internally for identifying the table. It's auto-generated, however, if you need it set to a custom value (ex: server-side rendering), you can set it via this property.
tableBodyHeightstring'auto'CSS string for the height of the table (ex: '500px', '100%', 'auto').
tableBodyMaxHeightstringCSS string for the height of the table (ex: '500px', '100%', 'auto').
textLabelsobjectUser provided labels to localize text.
viewColumnsbooleantrueShow/hide viewColumns icon from toolbar.

Customize Columns

在每个列对象上,您可以使用“选项”属性根据自己的喜好自定义列。 例子:

const columns = [
 {
  name: "Name",
  options: {
   filter: true,
   sort: false
  }
 },
 ...
];

Column:

NameTypeDescription
namestringName of column (This field is required)
labelstringColumn Header Name override
optionsobjectOptions for customizing column

Column Options:

NameTypeDefaultDescription
customBodyRenderfunctionFunction that returns a string or React component. Used to display data within all table cells of a given column. The value returned from this function will be used for filtering in the filter dialog. If this isn't need, you may want to consider customBodyRenderLite instead. function(value, tableMeta, updateValue) => string|React Component Example
customBodyRenderLitefunctionFunction that returns a string or React component. Used to display data within all table cells of a given column. This method performs better than customBodyRender but has the following caveats:

  • The value returned from this function is not used for filtering, so the filter dialog will use the raw data from the data array.
  • This method only gives you the dataIndex and rowIndex, leaving you to lookup the column value.

function(dataIndex, rowIndex) => string|React Component Example
customHeadLabelRenderfunctionFunction that returns a string or React component. Used for creating a custom header to a column. This method only affects the display in the table's header, other areas of the table (such as the View Columns popover), will use the column's label. function(columnMeta : object) => string|React Component
customFilterListOptionsobject(These options only affect the filter chips that display after filters are selected. To modify the filters themselves, see filterOptions)

  • render: function that returns a string or array of strings used as the chip label(s). function(value) => string OR arrayOfStrings Example
  • update: function that returns a filterList (see above) allowing for custom filter updates when removing the filter chip. filterType must be set to "custom". function(filterList, filterPos, index) => filterList Example

customHeadRenderfunctionFunction that returns a string or React component. Used as display for column header. function(columnMeta, handleToggleColumn, sortOrder) => string|React Component
displayboolean or stringtrueDisplay column in table. Possible values:

  • true: Column is visible and toggleable via the View Columns popover in the Toolbar.
  • false: Column is not visible but can be made visible via the View Columns popover in the Toolbar.
  • excluded: Column is not visible and not toggleable via the View Columns popover in the Toolbar.

另请参阅:viewColumnsfilter 选项。

downloadbooleantrueDisplay column in CSV download file.
draggablebooleantrueDetermines if a column can be dragged. The draggableColumns.enabled option must also be true.
emptybooleanfalseThis denotes whether the column has data or not (for use with intentionally empty columns).
filterbooleantrueDisplay column in filter list.
filterListarrayFilter value list Example
filterOptionsobject

这些选项会影响过滤器对话框中的过滤器显示和功能。 要修改选择过滤器后显示的过滤器芯片,请参阅 customFilterListOptions

此选项是用于自定义过滤器显示和过滤工作方式的多个选项的对象。

  • names: custom names for the filter fields Example
  • logic: custom filter logic Example
  • display(filterList, onChange(filterList, index, column), index, column, filterData): Custom rendering inside the filter dialog Example. filterList must be of the same type in the main column options, that is an array of arrays, where each array corresponds to the filter list for a given column.
  • renderValue: A function to customize filter choices Example. Example use case: changing empty strings to "(empty)" in a dropdown.
  • fullWidth (boolean): Will force a filter option to take up the grid's full width.

filterTypestring'dropdown'Choice of filtering view. Takes priority over global filterType option.enum('checkbox', 'dropdown', 'multiselect', 'textField', 'custom') Use 'custom' if you are supplying your own rendering via filterOptions.
hintstringDisplay hint icon with string as tooltip on hover.
printbooleantrueDisplay column when printing.
searchablebooleantrueExclude/include column from search results.
setCellHeaderPropsfunctionIs called for each header cell and allows you to return custom props for the header cell based on its data. function(columnMeta: object) => object Example
setCellPropsfunctionIs called for each cell and allows to you return custom props for this cell based on its data. function(cellValue: string, rowIndex: number, columnIndex: number) => object Example
sortbooleantrueEnable/disable sorting on column.
sortComparefunctionCustom sort function for the column. Takes in an order string and returns a function that compares the two column values. If this method and options.customSort are both defined, this method will take precedence. (order) => ({data: val1}, {data: val2}) => number Example
sortDescFirstbooleanfalseCauses the first click on a column to sort by desc rather than asc. Example
sortThirdClickResetbooleanfalseAllows for a third click on a column header to undo any sorting on the column. Example
viewColumnsbooleantrueAllow user to toggle column visibility through 'View Column' list.

customHeadRender 使用以下参数调用:

function(columnMeta: {
  customHeadRender: func,
  display: enum('true', 'false', 'excluded'),
  filter: boolean,
  sort: boolean,
  download: boolean,
  empty: boolean,
  index: number,
  label: string,
  name: string,
  print: boolean,
  searchable: boolean,
  viewColumns: boolean
}, handleToggleColumn: function(columnIndex))

customBodyRender 使用以下参数调用:

function(value: any, tableMeta: {
  rowIndex: number,
  columnIndex: number,
  columnData: array, // Columns Options object
  rowData: array, // Full row data
  tableData: array, // Full table data - Please use currentTableData instead
  currentTableData: array, // The current table data
  tableState: {
    announceText: null|string,
    page: number,
    rowsPerPage: number,
    filterList: array,
    selectedRows: {
      data: array,
      lookup: object,
    },
    showResponsive: boolean,
    searchText: null|string,
  },
}, updateValue: function)

Plug-ins

该表适用于许多领域的插件,尤其是在 customRender 函数中。 这些渲染功能的许多用例都很常见,因此您可以使用一组插件。

Available Plug-ins:

NameTypeDefaultDescription
debounceSearchRenderfunctionFunction that returns a function for the customSearchRender method. This plug-in allows you to create a debounced search which can be useful for server-side tables and tables with large data sets. function(debounceWait) => function Example

Customize Styling

使用 Material-UI 主题覆盖将允许您根据自己的喜好自定义样式。 首先,确定您要定位哪个组件,然后查找覆盖类名。 让我们从一个简单的例子开始,我们将把正文单元格的背景颜色更改为红色:

import React from "react";
import MUIDataTable from "mui-datatables";
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';

class BodyCellExample extends React.Component {

  getMuiTheme = () => createMuiTheme({
    overrides: {
      MUIDataTableBodyCell: {
        root: {
          backgroundColor: "#FF0000"
        }
      }
    }
  })

  render() {

    return (
      <MuiThemeProvider theme={this.getMuiTheme()}>
        <MUIDataTable title={"ACME Employee list"} data={data} columns={columns} options={options} />
      </MuiThemeProvider>
    );

  }
}

Custom Components

您可以传递自定义组件以进一步自定义表格:

import React from "react";
import Chip from '@material-ui/core/Chip';
import MUIDataTable, { TableFilterList } from "mui-datatables";

const CustomChip = ({ label, onDelete }) => {
    return (
        <Chip
            variant="outlined"
            color="secondary"
            label={label}
            onDelete={onDelete}
        />
    );
};

const CustomFilterList = (props) => {
    return <TableFilterList {...props} ItemComponent={CustomChip} />;
};

class CustomDataTable extends React.Component {
    render() {
        return (
            <MUIDataTable
                columns={columns}
                data={data}
                components={{
                  TableFilterList: CustomFilterList,
                }}
            />
        );
    }
}

支持的可自定义组件:

  • Checkbox - A special 'data-description' prop lets you differentiate checkboxes Example. Valid values: ['row-select', 'row-select-header', 'table-filter', 'table-view-col'].The dataIndex is also passed via the "data-index" prop.
  • ExpandButton Example
  • TableBody
  • TableViewCol - The component that displays the view/hide list of columns on the toolbar.
  • TableFilterList - You can pass ItemComponent prop to render custom filter list item.
  • TableFooter
  • TableHead
  • TableResize
  • TableToolbar
  • TableToolbarSelect
  • Tooltip

有关详细信息,请参阅此 示例。 此外,所有示例都可以在我们的 CodeSandbox 上实时查看。

Remote Data

如果您希望使用远程数据集或在远程服务器上处理分页、过滤和排序,您可以使用以下选项:

const options = {
  serverSide: true,
  onTableChange: (action, tableState) => {
    this.xhrRequest('my.api.com/tableData', result => {
      this.setState({ data: result });
    });
  }
};

查看示例 Click Here

Localization

这个包决定引入另一个库来执行本地化的成本太高. 相反,覆盖所有文本标签(数量不多)的能力是通过选项属性 textLabels 提供的。 可用字符串:

const options = {
  ...
  textLabels: {
    body: {
      noMatch: "Sorry, no matching records found",
      toolTip: "Sort",
      columnHeaderTooltip: column => `Sort for ${column.label}`
    },
    pagination: {
      next: "Next Page",
      previous: "Previous Page",
      rowsPerPage: "Rows per page:",
      displayRows: "of",
    },
    toolbar: {
      search: "Search",
      downloadCsv: "Download CSV",
      print: "Print",
      viewColumns: "View Columns",
      filterTable: "Filter Table",
    },
    filter: {
      all: "All",
      title: "FILTERS",
      reset: "RESET",
    },
    viewColumns: {
      title: "Show Columns",
      titleAria: "Show/Hide Table Columns",
    },
    selectedRows: {
      text: "row(s) selected",
      delete: "Delete",
      deleteAria: "Delete Selected Rows",
    },
  }
  ...
}

Contributing

感谢您对图书馆和 github 社区感兴趣!

以下命令应该可以帮助您入门:

npm i
npm run dev

在浏览器中打开 http://localhost:5050/ 在

本地进行更改后,您可以使用 npm test 运行测试套件。

License

此存储库中包含的文件已根据 MIT 许可证获得许可。

Thanks

感谢 BrowserStack 提供允许我们在真实浏览器中进行测试的基础设施。

MUI-Datatables - Datatables for Material-UI

Build StatusNPM DownloadsCoverage Statusnpm version

MUI-Datatables is a responsive datatables component built on Material-UI. It comes with features like filtering, resizable columns, view/hide columns, draggable columns, search, export to CSV download, printing, selectable rows, expandable rows, pagination, and sorting. On top of the ability to customize styling on most views, there are three responsive modes "vertical", "standard", and "simple" for mobile/tablet devices.

Version 3 has been released! You can read about the updates here!

Table of contents

Install

npm install mui-datatables --save

If your project doesn't already use them, you need to install @material-ui/core and @material-ui/icons as well.

Demo

Edit react-to-print

Browse live demos of all examples in this repo in here!

Usage

For a simple table:

import MUIDataTable from "mui-datatables";

const columns = ["Name", "Company", "City", "State"];

const data = [
 ["Joe James", "Test Corp", "Yonkers", "NY"],
 ["John Walsh", "Test Corp", "Hartford", "CT"],
 ["Bob Herm", "Test Corp", "Tampa", "FL"],
 ["James Houston", "Test Corp", "Dallas", "TX"],
];

const options = {
  filterType: 'checkbox',
};

<MUIDataTable
  title={"Employee List"}
  data={data}
  columns={columns}
  options={options}
/>

Or customize columns:

import MUIDataTable from "mui-datatables";

const columns = [
 {
  name: "name",
  label: "Name",
  options: {
   filter: true,
   sort: true,
  }
 },
 {
  name: "company",
  label: "Company",
  options: {
   filter: true,
   sort: false,
  }
 },
 {
  name: "city",
  label: "City",
  options: {
   filter: true,
   sort: false,
  }
 },
 {
  name: "state",
  label: "State",
  options: {
   filter: true,
   sort: false,
  }
 },
];

const data = [
 { name: "Joe James", company: "Test Corp", city: "Yonkers", state: "NY" },
 { name: "John Walsh", company: "Test Corp", city: "Hartford", state: "CT" },
 { name: "Bob Herm", company: "Test Corp", city: "Tampa", state: "FL" },
 { name: "James Houston", company: "Test Corp", city: "Dallas", state: "TX" },
];

const options = {
  filterType: 'checkbox',
};

<MUIDataTable
  title={"Employee List"}
  data={data}
  columns={columns}
  options={options}
/>

API

<MUIDataTable />

The component accepts the following props:

NameTypeDescription
titlearrayTitle used to caption table
columnsarrayColumns used to describe table. Must be either an array of simple strings or objects describing a column
dataarrayData used to describe table. Must be either an array containing objects of key/value pairs with values that are strings or numbers, or arrays of strings or numbers (Ex: data: [{"Name": "Joe", "Job Title": "Plumber", "Age": 30}, {"Name": "Jane", "Job Title": "Electrician", "Age": 45}] or data: [["Joe", "Plumber", 30], ["Jane", "Electrician", 45]]). The customBodyRender and customBodyRenderLite options can be used to control the data diaplay.
optionsobjectOptions used to describe table
componentsobjectCustom components used to render the table

Options:

NameTypeDefaultDescription
caseSensitivebooleanfalseEnable/disable case sensitivity for search.
confirmFiltersbooleanfalseWorks in conjunction with the customFilterDialogFooter option and makes it so filters have to be confirmed before being applied to the table. When this option is true, the customFilterDialogFooter callback will receive an applyFilters function which, when called, will apply the filters to the table. Example
columnOrderarrayAn array of numbers (column indices) indicating the order the columns should be displayed in. Defaults to the order provided by the Columns prop. This option is useful if you'd like certain columns to swap positions (see draggableColumns option).
countnumberUser provided override for total number of rows.
customFilterDialogFooterfunctionAdd a custom footer to the filter dialog. customFilterDialogFooter(curentFilterList: array, applyFilters: function) => React Component
customFooterfunctionRender a custom table footer. function(count, page, rowsPerPage, changeRowsPerPage, changePage,textLabels: object) => string|React Component Example
customRowRenderfunctionOverride default row rendering with custom function. customRowRender(data, dataIndex, rowIndex) => React Component
customSearchfunctionOverride default search with custom function. customSearch(searchQuery: string, currentRow: array, columns: array) => boolean
customSearchRenderfunctionRender a custom table search. customSearchRender(searchText: string, handleSearch, hideSearch, options) => React Component
customSortfunctionOverride default sorting with custom function. If you just need to override the sorting for a particular column, see the sortCompare method in the column options. function(data: array, colIndex: number, order: string) => array Example
customTableBodyFooterRenderfunctionRender a footer under the table body but above the table's standard footer. This is useful for creating footers for individual columns. Example
customToolbarfunctionRender a custom toolbar
customToolbarSelectfunctionRender a custom selected rows toolbar. function(selectedRows, displayData, setSelectedRows) => void
downloadbooleantrueShow/hide download icon from toolbar
downloadOptionsobjectsee ->An object of options to change the output of the CSV file:

  • filename: string
  • separator: string
  • filterOptions: object
    • useDisplayedColumnsOnly: boolean
    • useDisplayedRowsOnly: boolean

Default Value:{filename: 'tableDownload.csv', separator: ','}

draggableColumnsobject{}An object of options describing how dragging columns should work. The options are:

  • enabled:boolean: Indicates if draggable columns are enabled. Defaults to false.
  • transitionTime:number: The time in milliseconds it takes for columns to swap positions. Defaults to 300.

To disable the dragging of a particular column, see the "draggable" option in the columns options. Dragging a column to a new position updates the columnOrder array and triggers the onColumnOrderChange callback.
elevationnumber4Shadow depth applied to Paper component.
enableNestedDataAccessstring""If provided a non-empty string (ex: "."), it will use that value in the column's names to access nested data. For example, given a enableNestedDataAccess value of "." and a column name of "phone.cell", the column would use the value found in phone:{cell:"555-5555"}. Any amount of nesting will work. Example demonstrates the functionality.
expandableRowsbooleanfalseEnable/disable expandable rows. Example
expandableRowsHeaderbooleantrueShow/hide the expand all/collapse all row header for expandable rows.
expandableRowsOnClickbooleanfalseEnable/disable expand trigger when row is clicked. When False, only expand icon will trigger this action.
filterbooleantrueShow/hide filter icon from toolbar.
filterTypestringChoice of filtering view. enum('checkbox', 'dropdown', 'multiselect', 'textField', 'custom')
fixedHeaderbooleantrueEnable/disable a fixed header for the table Example
fixedSelectColumnbooleantrueEnable/disable fixed select column. Example
isRowExpandablefunctionEnable/disable expansion or collapse on certain expandable rows with custom function. Will be considered true if not provided. function(dataIndex: number, expandedRows: object(lookup: {dataIndex: number}, data: arrayOfObjects: {index: number, dataIndex: number})) => boolean.
isRowSelectablefunctionEnable/disable selection on certain rows with custom function. Returns true if not provided. function(dataIndex: number, selectedRows: object(lookup: {dataindex: boolean}, data: arrayOfObjects: {index, dataIndex})) => boolean.
jumpToPagebooleanfalseWhen true, this option adds a dropdown to the table's footer that allows a user to navigate to a specific page. Example
onCellClickfunctionCallback function that triggers when a cell is clicked. function(colData: any, cellMeta: { colIndex: number, rowIndex: number, dataIndex: number }) => void
onChangePagefunctionCallback function that triggers when a page has changed. function(currentPage: number) => void
onChangeRowsPerPagefunctionCallback function that triggers when the number of rows per page has changed. function(numberOfRows: number) => void
onColumnOrderChangefunctionCallback function that triggers when a column has been dragged to a new location. function(newColumnOrder:array, columnIndex:number, newPosition:number) => void
onColumnSortChangefunctionCallback function that triggers when a column has been sorted. function(changedColumn: string, direction: string) => void
onDownloadfunctionA callback function that triggers when the user downloads the CSV file. In the callback, you can control what is written to the CSV file. This method can be used to add the Excel specific BOM character (see this example). function(buildHead: (columns) => string, buildBody: (data) => string, columns, data) => string. Return false to cancel download of file.
onFilterChangefunctionCallback function that triggers when filters have changed. function(changedColumn: string, filterList: array, type: enum('checkbox', 'dropdown', 'multiselect', 'textField', 'custom', 'chip', 'reset'), changedColumnIndex, displayData) => void
onFilterChipClosefunctionCallback function that is triggered when a user clicks the "X" on a filter chip. function(index : number, removedFilter : string, filterList : array) => void Example
onFilterConfirmfunctionCallback function that is triggered when a user presses the "confirm" button on the filter popover. This occurs only if you've set confirmFilters option to true. function(filterList: array) => void Example
onFilterDialogClosefunctionCallback function that triggers when the filter dialog closes. function() => void
onFilterDialogOpenfunctionCallback function that triggers when the filter dialog opens. function() => void
onRowClickfunctionCallback function that triggers when a row is clicked. function(rowData: string[], rowMeta: { dataIndex: number, rowIndex: number }) => void
onRowExpansionChangefunctionCallback function that triggers when row(s) are expanded/collapsed. function(currentRowsExpanded: array, allRowsExpanded: array, rowsExpanded: array) => void
onRowsDeletefunctionCallback function that triggers when row(s) are deleted. function(rowsDeleted: object(lookup: {[dataIndex]: boolean}, data: arrayOfObjects: {index: number, dataIndex: number}), newTableData) => void OR false (Returning false prevents row deletion.)
onRowSelectionChangefunctionCallback function that triggers when row(s) are selected/deselected. function(currentRowsSelected: array, allRowsSelected: array, rowsSelected: array) => void
onSearchChangefunctionCallback function that triggers when the search text value has changed. function(searchText: string) => void
onSearchClosefunctionCallback function that triggers when the searchbox closes. function() => void
onSearchOpenfunctionCallback function that triggers when the searchbox opens. function() => void
onTableChangefunctionCallback function that triggers when table state has changed. function(action: string, tableState: object) => void
onTableInitfunctionCallback function that triggers when table state has been initialized. function(action: string, tableState: object) => void
onViewColumnsChangefunctionCallback function that triggers when a column view has been changed. Previously known as onColumnViewChange. function(changedColumn: string, action: string) => void
pagenumberUser provided page for pagination.
paginationbooleantrueEnable/disable pagination.
printbooleantrueShow/hide print icon from toolbar.
renderExpandableRowfunctionRender expandable row. function(rowData, rowMeta) => React Component Example
resizableColumnsbooleanfalseEnable/disable resizable columns.
responsivestring'stacked'Enable/disable responsive table views. Options:

  • "vertical" (default value): In smaller views the table cells will collapse such that the heading is to the left of the cell value.
  • "standard": Table will stay in the standard mode but make small changes to better fit the allocated space.
  • "simple": On very small devices the table rows will collapse into simple display.

Example
rowHoverbooleantrueEnable/disable hover style over rows.
rowsExpandedarrayUser provided expanded rows.
rowsPerPagenumber10Number of rows allowed per page.
rowsPerPageOptionsarray[10,15,100]Options to provide in pagination for number of rows a user can select.
rowsSelectedarrayUser provided array of numbers (dataIndexes) which indicates the selected rows.
searchbooleantrueShow/hide search icon from toolbar.
searchPlaceholderstringSearch text placeholder. Example
searchPropsobject{}Props applied to the search text box. You can set method callbacks like onBlur, onKeyUp, etc, this way. Example
searchOpenbooleanfalseInitially displays search bar.
searchTextstringSearch text for the table.
selectableRowsstring'multiple'Indicates if rows can be selected. Options are "multiple", "single", "none".
selectableRowsHeaderbooleantrueShow/hide the select all/deselect all checkbox header for selectable rows.
selectableRowsHideCheckboxesbooleanfalseHides the checkboxes that appear when selectableRows is set to "multiple" or "single". Can provide a more custom UX, especially when paired with selectableRowsOnClick.
selectableRowsOnClickbooleanfalseEnable/disable select toggle when row is clicked. When False, only checkbox will trigger this action.
selectToolbarPlacementstring'replace'Controls the visibility of the Select Toolbar, options are 'replace' (select toolbar replaces default toolbar when a row is selected), 'above' (select toolbar will appear above default toolbar when a row is selected) and 'none' (select toolbar will never appear)
serverSidebooleanfalseEnable remote data source.
setFilterChipPropsfunctionIs called for each filter chip and allows you to place custom props on a filter chip. function(colIndex: number, colName: string, filterValue: string) => object Example
setRowPropsfunctionIs called for each row and allows you to return custom props for this row based on its data. function(row: array, dataIndex: number, rowIndex: number) => object Example
setTablePropsfunctionIs called for the table and allows you to return custom props for the table based on its data. function() => object Example
sortbooleantrueEnable/disable sort on all columns.
sortFilterListbooleantrueEnable/disable alphanumeric sorting of filter lists.
sortOrderobject{}Sets the column to sort by and its sort direction. To remove/reset sorting, input in an empty object. The object options are the column name and the direction: name: string, direction: enum('asc', 'desc') Example
tableIdstringauto generatedA string that is used internally for identifying the table. It's auto-generated, however, if you need it set to a custom value (ex: server-side rendering), you can set it via this property.
tableBodyHeightstring'auto'CSS string for the height of the table (ex: '500px', '100%', 'auto').
tableBodyMaxHeightstringCSS string for the height of the table (ex: '500px', '100%', 'auto').
textLabelsobjectUser provided labels to localize text.
viewColumnsbooleantrueShow/hide viewColumns icon from toolbar.

Customize Columns

On each column object, you have the ability to customize columns to your liking with the 'options' property. Example:

const columns = [
 {
  name: "Name",
  options: {
   filter: true,
   sort: false
  }
 },
 ...
];

Column:

NameTypeDescription
namestringName of column (This field is required)
labelstringColumn Header Name override
optionsobjectOptions for customizing column

Column Options:

NameTypeDefaultDescription
customBodyRenderfunctionFunction that returns a string or React component. Used to display data within all table cells of a given column. The value returned from this function will be used for filtering in the filter dialog. If this isn't need, you may want to consider customBodyRenderLite instead. function(value, tableMeta, updateValue) => string|React Component Example
customBodyRenderLitefunctionFunction that returns a string or React component. Used to display data within all table cells of a given column. This method performs better than customBodyRender but has the following caveats:

  • The value returned from this function is not used for filtering, so the filter dialog will use the raw data from the data array.
  • This method only gives you the dataIndex and rowIndex, leaving you to lookup the column value.

function(dataIndex, rowIndex) => string|React Component Example
customHeadLabelRenderfunctionFunction that returns a string or React component. Used for creating a custom header to a column. This method only affects the display in the table's header, other areas of the table (such as the View Columns popover), will use the column's label. function(columnMeta : object) => string|React Component
customFilterListOptionsobject(These options only affect the filter chips that display after filters are selected. To modify the filters themselves, see filterOptions)

  • render: function that returns a string or array of strings used as the chip label(s). function(value) => string OR arrayOfStrings Example
  • update: function that returns a filterList (see above) allowing for custom filter updates when removing the filter chip. filterType must be set to "custom". function(filterList, filterPos, index) => filterList Example

customHeadRenderfunctionFunction that returns a string or React component. Used as display for column header. function(columnMeta, handleToggleColumn, sortOrder) => string|React Component
displayboolean or stringtrueDisplay column in table. Possible values:

  • true: Column is visible and toggleable via the View Columns popover in the Toolbar.
  • false: Column is not visible but can be made visible via the View Columns popover in the Toolbar.
  • excluded: Column is not visible and not toggleable via the View Columns popover in the Toolbar.

See also: viewColumns and filter options.

downloadbooleantrueDisplay column in CSV download file.
draggablebooleantrueDetermines if a column can be dragged. The draggableColumns.enabled option must also be true.
emptybooleanfalseThis denotes whether the column has data or not (for use with intentionally empty columns).
filterbooleantrueDisplay column in filter list.
filterListarrayFilter value list Example
filterOptionsobject

These options affect the filter display and functionality from the filter dialog. To modify the filter chips that display after selecting filters, see customFilterListOptions

This option is an object of several options for customizing the filter display and how filtering works.

  • names: custom names for the filter fields Example
  • logic: custom filter logic Example
  • display(filterList, onChange(filterList, index, column), index, column, filterData): Custom rendering inside the filter dialog Example. filterList must be of the same type in the main column options, that is an array of arrays, where each array corresponds to the filter list for a given column.
  • renderValue: A function to customize filter choices Example. Example use case: changing empty strings to "(empty)" in a dropdown.
  • fullWidth (boolean): Will force a filter option to take up the grid's full width.

filterTypestring'dropdown'Choice of filtering view. Takes priority over global filterType option.enum('checkbox', 'dropdown', 'multiselect', 'textField', 'custom') Use 'custom' if you are supplying your own rendering via filterOptions.
hintstringDisplay hint icon with string as tooltip on hover.
printbooleantrueDisplay column when printing.
searchablebooleantrueExclude/include column from search results.
setCellHeaderPropsfunctionIs called for each header cell and allows you to return custom props for the header cell based on its data. function(columnMeta: object) => object Example
setCellPropsfunctionIs called for each cell and allows to you return custom props for this cell based on its data. function(cellValue: string, rowIndex: number, columnIndex: number) => object Example
sortbooleantrueEnable/disable sorting on column.
sortComparefunctionCustom sort function for the column. Takes in an order string and returns a function that compares the two column values. If this method and options.customSort are both defined, this method will take precedence. (order) => ({data: val1}, {data: val2}) => number Example
sortDescFirstbooleanfalseCauses the first click on a column to sort by desc rather than asc. Example
sortThirdClickResetbooleanfalseAllows for a third click on a column header to undo any sorting on the column. Example
viewColumnsbooleantrueAllow user to toggle column visibility through 'View Column' list.

customHeadRender is called with these arguments:

function(columnMeta: {
  customHeadRender: func,
  display: enum('true', 'false', 'excluded'),
  filter: boolean,
  sort: boolean,
  download: boolean,
  empty: boolean,
  index: number,
  label: string,
  name: string,
  print: boolean,
  searchable: boolean,
  viewColumns: boolean
}, handleToggleColumn: function(columnIndex))

customBodyRender is called with these arguments:

function(value: any, tableMeta: {
  rowIndex: number,
  columnIndex: number,
  columnData: array, // Columns Options object
  rowData: array, // Full row data
  tableData: array, // Full table data - Please use currentTableData instead
  currentTableData: array, // The current table data
  tableState: {
    announceText: null|string,
    page: number,
    rowsPerPage: number,
    filterList: array,
    selectedRows: {
      data: array,
      lookup: object,
    },
    showResponsive: boolean,
    searchText: null|string,
  },
}, updateValue: function)

Plug-ins

The table lends itself to plug-ins in many areas, especially in the customRender functions. Many use cases for these render functions are common, so a set of plug-ins are available that you can use.

Available Plug-ins:

NameTypeDefaultDescription
debounceSearchRenderfunctionFunction that returns a function for the customSearchRender method. This plug-in allows you to create a debounced search which can be useful for server-side tables and tables with large data sets. function(debounceWait) => function Example

Customize Styling

Using Material-UI theme overrides will allow you to customize styling to your liking. First, determine which component you would want to target and then lookup the override classname. Let's start with a simple example where we will change the background color of a body cell to be red:

import React from "react";
import MUIDataTable from "mui-datatables";
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles';

class BodyCellExample extends React.Component {

  getMuiTheme = () => createMuiTheme({
    overrides: {
      MUIDataTableBodyCell: {
        root: {
          backgroundColor: "#FF0000"
        }
      }
    }
  })

  render() {

    return (
      <MuiThemeProvider theme={this.getMuiTheme()}>
        <MUIDataTable title={"ACME Employee list"} data={data} columns={columns} options={options} />
      </MuiThemeProvider>
    );

  }
}

Custom Components

You can pass custom components to further customize the table:

import React from "react";
import Chip from '@material-ui/core/Chip';
import MUIDataTable, { TableFilterList } from "mui-datatables";

const CustomChip = ({ label, onDelete }) => {
    return (
        <Chip
            variant="outlined"
            color="secondary"
            label={label}
            onDelete={onDelete}
        />
    );
};

const CustomFilterList = (props) => {
    return <TableFilterList {...props} ItemComponent={CustomChip} />;
};

class CustomDataTable extends React.Component {
    render() {
        return (
            <MUIDataTable
                columns={columns}
                data={data}
                components={{
                  TableFilterList: CustomFilterList,
                }}
            />
        );
    }
}

Supported customizable components:

  • Checkbox - A special 'data-description' prop lets you differentiate checkboxes Example. Valid values: ['row-select', 'row-select-header', 'table-filter', 'table-view-col'].The dataIndex is also passed via the "data-index" prop.
  • ExpandButton Example
  • TableBody
  • TableViewCol - The component that displays the view/hide list of columns on the toolbar.
  • TableFilterList - You can pass ItemComponent prop to render custom filter list item.
  • TableFooter
  • TableHead
  • TableResize
  • TableToolbar
  • TableToolbarSelect
  • Tooltip

For more information, please see this example. Additionally, all examples can be viewed live at our CodeSandbox.

Remote Data

If you are looking to work with remote data sets or handle pagination, filtering, and sorting on a remote server you can do that with the following options:

const options = {
  serverSide: true,
  onTableChange: (action, tableState) => {
    this.xhrRequest('my.api.com/tableData', result => {
      this.setState({ data: result });
    });
  }
};

To see an example Click Here

Localization

This package decided that the cost of bringing in another library to perform localizations would be too expensive. Instead the ability to override all text labels (which aren't many) is offered through the options property textLabels. The available strings:

const options = {
  ...
  textLabels: {
    body: {
      noMatch: "Sorry, no matching records found",
      toolTip: "Sort",
      columnHeaderTooltip: column => `Sort for ${column.label}`
    },
    pagination: {
      next: "Next Page",
      previous: "Previous Page",
      rowsPerPage: "Rows per page:",
      displayRows: "of",
    },
    toolbar: {
      search: "Search",
      downloadCsv: "Download CSV",
      print: "Print",
      viewColumns: "View Columns",
      filterTable: "Filter Table",
    },
    filter: {
      all: "All",
      title: "FILTERS",
      reset: "RESET",
    },
    viewColumns: {
      title: "Show Columns",
      titleAria: "Show/Hide Table Columns",
    },
    selectedRows: {
      text: "row(s) selected",
      delete: "Delete",
      deleteAria: "Delete Selected Rows",
    },
  }
  ...
}

Contributing

Thanks for taking an interest in the library and the github community!

The following commands should get you started:

npm i
npm run dev

open http://localhost:5050/ in browser

After you make your changes locally, you can run the test suite with npm test.

License

The files included in this repository are licensed under the MIT license.

Thanks

Thank you to BrowserStack for providing the infrastructure that allows us to test in real browsers.

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文