1.0.8 • Published 5 years ago

thdatatable v1.0.8

Weekly downloads
-
License
ISC
Repository
-
Last release
5 years ago

MUI-Datatables - Datatables for Material-UI

Build Status NPM Downloads Coverage Status dependencies Status npm version

MUI-Datatables is a data tables component built on Material-UI. It comes with features like filtering, resizable + view/hide 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 "stacked", "scrollMaxHeight", and "scrollFullHeight" for mobile/tablet devices.

Install

npm install mui-datatables --save

Demo

Edit react-to-print

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]) Use of arbitrary objects as data is not supported, and is deprecated. Consider using ids and mapping to external object data in custom renderers instead e.g. const data = [{"Name": "Joe", "ObjectData": 123}] --> const dataToMapInCustomRender = { 123: { foo: 'bar', baz: 'qux', ... } }
optionsobjectOptions used to describe table

Options:

NameTypeDefaultDescription
pagenumberUser provided starting page for pagination
countnumberUser provided override for total number of rows
serverSidebooleanfalseEnable remote data source
serverSideFilterListarray[]Sets the filter list display when using serverSide: true
rowsSelectedarrayUser provided selected rows
rowsExpandedarrayUser provided expanded rows
filterTypestringChoice of filtering view. enum('checkbox', 'dropdown', 'multiselect', 'textField', 'custom')
textLabelsobjectUser provided labels to localize text
paginationbooleantrueEnable/disable pagination
selectableRowsstring'multiple'Numbers of rows that can be selected. Options are "multiple", "single", "none". (Boolean options have been deprecated.)
selectableRowsOnClickbooleanfalseEnable/disable select toggle when row is clicked. When False, only checkbox will trigger this action.
disableToolbarSelectbooleanfalseEnable/disable the Select Toolbar that appears when a row is selected.
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.
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.
selectableRowsHeaderbooleantrueShow/hide the select all/deselect all checkbox header for selectable rows
expandableRowsbooleanfalseEnable/disable expandable rows
expandableRowsOnClickbooleanfalseEnable/disable expand trigger when row is clicked. When False, only expand icon will trigger this action.
renderExpandableRowfunctionRender expandable row. function(rowData, rowMeta) => React Component
resizableColumnsbooleanfalseEnable/disable resizable columns
customToolbarfunctionRender a custom toolbar
customToolbarSelectfunctionRender a custom selected rows toolbar. function(selectedRows, displayData, setSelectedRows) => void
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
customSortfunctionOverride default sorting with custom function. function(data: array, colIndex: number, order: string) => array
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
customFilterDialogFooterfunctionAdd a custom footer to the filter dialog. customFilterDialogFooter(filterList: array) => React Component
elevationnumber4Shadow depth applied to Paper component
caseSensitivebooleanfalseEnable/disable case sensitivity for search
responsivestring'stacked'Enable/disable responsive table views. Options: 'stacked', 'scrollMaxHeight' (limits height of table), 'scrollFullHeight' (table takes on as much height as needed to display all rows set in rowsPerPage) ('scroll' option has been deprecated in favor of scrollMaxHeight)
rowsPerPagenumber10Number of rows allowed per page
rowsPerPageOptionsarray10,15,100Options to provide in pagination for number of rows a user can select
rowHoverbooleantrueEnable/disable hover style over rows
fixedHeader DEPRECATED (use fixedHeaderOptions)booleantrueEnable/disable fixed header columns
fixedHeaderOptionsobject{xAxis: true, yAxis: true}Enable/disable fixed header columns according to axis in any combination desired Example
sortFilterListbooleantrueEnable/disable alphanumeric sorting of filter lists
sortbooleantrueEnable/disable sort on all columns
filterbooleantrueShow/hide filter icon from toolbar
searchbooleantrueShow/hide search icon from toolbar
searchOpenbooleanfalseInitially displays search bar
searchTextstringInitial search text
searchPlaceholderstringSearch text placeholder. Example
printbooleantrueShow/hide print icon from toolbar
downloadbooleantrueShow/hide download icon from toolbar
downloadOptionsobject{filename: 'tableDownload.csv', separator: ','}Options to change the output of the CSV file: filename: string, separator: string, filterOptions: object(useDisplayedColumnsOnly: boolean, useDisplayedRowsOnly: boolean)
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. function(buildHead: (columns) => string, buildBody: (data) => string, columns, data) => string. Return false to cancel download of file.
viewColumnsbooleantrueShow/hide viewColumns icon from toolbar
onRowsSelectfunctionCallback function that triggers when row(s) are selected. function(currentRowsSelected: array, allRowsSelected: array) => void
onRowsExpandfunctionCallback function that triggers when row(s) are expanded. function(currentRowsExpanded: array, allRowsExpanded: array) => void
onRowsDeletefunctionCallback function that triggers when row(s) are deleted. function(rowsDeleted: object(lookup: {[dataIndex]: boolean}, data: arrayOfObjects: {index: number, dataIndex: number})) => void OR false (Returning false prevents row deletion.)
onRowClickfunctionCallback function that triggers when a row is clicked. function(rowData: string[], rowMeta: { dataIndex: number, rowIndex: number }) => void
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
onSearchChangefunctionCallback function that triggers when the search text value has changed. function(searchText: string) => void
onSearchOpenfunctionCallback function that triggers when the searchbox opens. function() => void
onFilterDialogOpenfunctionCallback function that triggers when the filter dialog opens. function() => void
onFilterDialogClosefunctionCallback function that triggers when the filter dialog closes. function() => void
onFilterChangefunctionCallback function that triggers when filters have changed. function(changedColumn: string, filterList: array, type: enum('checkbox', 'dropdown', 'multiselect', 'textField', 'custom', 'chip', 'reset')) => void
onSearchClosefunctionCallback function that triggers when the searchbox closes. function() => void
onColumnSortChangefunctionCallback function that triggers when a column has been sorted. function(changedColumn: string, direction: string) => void
onColumnViewChangefunctionCallback function that triggers when a column view has been changed. function(changedColumn: string, action: string) => 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
setRowPropsfunctionIs called for each row and allows you to return custom props for this row based on its data. function(row: array, dataIndex: 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

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
displaystring'true'Display column in table. enum('true', 'false', 'excluded')
emptybooleanfalseThis denotes whether the column has data or not (for use with intentionally empty columns)
viewColumnsbooleantrueAllow user to toggle column visibility through 'View Column' list
filterListarrayFilter value list Example
filterOptions{names, logic, display}(These options affect the filter display and functionality from the filter dialog. To modify the filter chips that display after selecting filters, see customFilterListOptions) With filter options, it's possible to use custom names for the filter fields Example, custom filter logic Example, and custom rendering Example
customFilterListRender DEPRECATED (use customFilterListOptions)functionFunction that returns a string or array of strings used as the chip label(s). function(value) => string OR arrayOfStrings Example
customFilterListOptions{render: function, update: function}(These options only affect the filter chips that display after filters are selected. To modify the filters themselves, see filterOptions) render returns a string or array of strings used as the chip label(s). function(value) => string OR arrayOfStrings, update returns a filterList (see above) allowing for custom filter updates when removing the filter chip Example
filterbooleantrueDisplay column in filter list
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.
sortbooleantrueEnable/disable sorting on column
searchablebooleantrueExclude/include column from search results
sortDirectionstringSet default sort order enum('asc', 'desc', 'none') (null option has been deprecated, use 'none' instead)
printbooleantrueDisplay column when printing
downloadbooleantrueDisplay column in CSV download file
hintstringDisplay hint icon with string as tooltip on hover.
customHeadRenderfunctionFunction that returns a string or React component. Used as display for column header. function(columnMeta, handleToggleColumn) => string|React Component
customBodyRenderfunctionFunction that returns a string or React component. Used as display data within all table cells of a given column. function(value, tableMeta, updateValue) => string|React Component 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
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

customHeadRender is called with these arguments:

function(columnMeta: {
  customHeadRender: func,
  display: enum('true', 'false', 'excluded'),
  filter: boolean,
  sort: boolean,
  sortDirection: 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
  tableState: {
    announceText: null|string,
    page: number,
    rowsPerPage: number,
    filterList: array,
    selectedRows: {
      data: array,
      lookup: object,
    },
    showResponsive: boolean,
    searchText: null|string,
  },
}, updateValue: function)

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

  }
}

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.