0.11.0 • Published 4 years ago

mui-dt v0.11.0

Weekly downloads
1
License
MIT
Repository
github
Last release
4 years ago

MUI-DT - Datatables for Material-UI

Build Status Coverage Status npm version

MUI-DT 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 3 display modes "stacked", "scroll", and "responsiveStacked".

You can try the table out live in a CodeSandbox here: https://codesandbox.io/s/github/patorjk/mui-dt

Install

npm install mui-dt --save

Usage

For a simple table:

import MuiDt from "mui-dt";

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',
};

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

Or customize columns:

import MuiDt from "mui-dt";

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',
};

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

Cell data values should be a string, number, boolean, undefined, null, or array. Cells with data values of objects {} can cause issues.

API

<MUIDT />

The component accepts the following props:

NameTypeDescription
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 an array containing objects. (Arrays containing just strings or numbers also supported)
optionsobjectOptions used to describe table
titlearrayTitle used to caption table

Options:

NameTypeDefaultDescription
caseSensitivebooleanfalseEnable/disable case sensitivity for search.
checkboxColorstring'primary'Color of the checkbox. Options are: 'primary', 'secondary', 'default'.
customFooterfunctionRender a custom table footer. function(count, page, rowsPerPage, changeRowsPerPage, changePage,textLabels: object) => string|React Component Example
customRowRenderfunctionOverride default row rendering with custom function. You probably don't need to use this, see the setRowProps method instead (this render method is more powerful, but it will be more work for you). 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. For a debounced search, there is a plug-in called "debounceSearchRender" you can use here. See the plug-in section for more details. customSearchRender(searchText: string, handleSearch, hideSearch, options) => React Component
customSortfunctionOverride default sorting with custom function. function(data: array, colIndex: number, order: string) => array
customToolbarfunctionRender a custom toolbar.
customToolbarSelectfunctionRender a custom selected rows toolbar. function(selectedRows, displayData, setSelectedRows) => void
countnumberUser provided override for total number of rows.
disableSelectToolbarbooleanfalseEnable/disable the Select Toolbar that appears when a row is selected.
displayModestring'stacked'The display mode for the table. Options: 'stacked', 'scroll', or 'responsiveStacked'. 'responsiveStacked' will have the table in 'stacked' mode when on smaller screens and 'scroll' mode on larger screens. Use the 'tableBodyHeight to adjust the table's height.
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)
elevationnumber4Shadow depth applied to Paper component.
expandableRowsbooleanfalseEnable/disable expandable rows.
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')
filterPopoverOptionsobject{mustConfirm: false, confirmButtonLabel: 'Submit'}Options to change the filter popover. Can be useful for serverSide filtering where you want to confirm the filters before applying them. Options: mustConfirm: boolean, confirmButtonLabel: string
fixedHeaderbooleantrueEnable/disable fixed header columns.
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})) => bool.
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: number, dataIndex: number})) => boolean.
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
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
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.
onFilterChipClosefunctionCallback function that triggers when a filter is removed via the user pressing X on a filter chip to remove one of the filters. function(changedColumnIndex: number, removedFilter: array, filterList: array,) => void
onFilterChangefunctionCallback function that triggers when filters have changed. function(changedColumnIndex: number, filterList: array) => void
onFilterConfirmfunctionCallback function that is triggered when a user presses the "confirm" button on the filter popover. This occurs only if you've set filterPopoverOptions.mustConfirm option to true. function(filterList: array) => void
onRowClickfunctionCallback function that triggers when a row is clicked. function(rowData: string[], rowMeta: { dataIndex: number, rowIndex: number }) => void
onRowExpansionChangefunctionCallback function that triggers when a row is expanded or collapsed. The rowsExpanded parameter can be used to save off the value for options.rowsExpanded for state changes. function(affectedRows: array, allRowsExpanded: array, rowsExpanded: array) => void Example
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.)
onRowSelectionChangefunctionCallback function that triggers when row(s) are selected/unselected. If setting state, the rowsSelected parameter can be used to set options.rowsSelected. function(affectedRows: array, allSelectedRows: array, rowsSelected: rowsSelected) => void Example
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
pagenumberUser provided starting page for pagination.
paginationbooleantrueEnable/disable pagination.
printbooleantrueShow/hide print icon from toolbar.
renderExpandableRowfunctionRender expandable row. function(rowData, rowMeta) => React Component
resizableColumnsbooleanfalseEnable/disable resizable columns.
rowHoverbooleantrueEnable/disable hover style over rows.
rowsExpandedarrayUser provided expanded rows.
rowsPerPagenumber10Number of rows allowed per page.
rowsPerPageOptionsarray10,15,100Options to provide in pagination for number of rows a user can select.
rowsSelectedarrayUser provided selected rows.
selectableRowsstring'multiple'Numbers of rows that can be selected. Options are 'multiple', 'single', 'none'.
selectableRowsHeaderbooleantrueShow/hide the select all/deselect all checkbox header for selectable rows.
selectableRowsOnClickbooleanfalseEnable/disable select toggle when row is clicked. When False, only checkbox will trigger this action.
searchbooleantrueShow/hide search icon from toolbar.
searchTextstringInitial search text.
searchPropsobject{}Props applied to the search text box. You can set the placeholder text this way as well as add method callbacks like onBlur, onKeyUp, etc. 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) => object Example
serverSidebooleanfalseEnable remote data source. When setting this option to true, the developer is responsible for the filtering, sorting, etc, of the data and for updating the options and columns inputs to the table. Example
showSearchbooleanfalseShows the search bar when the table toolbar rendered. Example
sortbooleantrueEnable/disable sort on all columns.
sortOrderobject{}Sets the column to sort by and the sort direction. To remove/reset sorting, input in an empty object. Options: columnName: string, sortDirection: enum('asc', 'desc') Example
sortFilterListbooleantrueEnable/disable alphanumeric sorting of filter lists.
tablePropsobject{}Props applied to the table. You can set the table up to be a "dense" table this way. Example
tableBodyHeightstring'none'The height of the body of the table. This is a CSS string value (ex: '500px', 'none', '100%', etc). Example
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 a table cell of a given column. function(value, tableMeta, updateValue) => string|React Component Example
customBodyRenderLitefunctionFunction that returns a string or React component. Used to display data within a table cell of a given column. This function has better performance than customBodyRender at the cost of some functionality (different arguments and filtering is done with pre-processed data). If you have a client-side table with 1000+ rows, this is what you should use. function(dataIndex, rowIndex) => string|React Component Example
customHeadLabelRenderfunctionFunction that returns a string or React component. Used to replace the display for the column header's label. function(columnMeta, sortOrder, handleToggleColumn) => string|React Component
customHeadRenderfunctionFunction that returns a string or React component. Used as display for column header. In most cases you want customHeadLabelRender instead, as this method is for overriding the full header cell. function(columnMeta, handleToggleColumn) => string|React Component
displaystring'true'Display column in table. enum('true', 'false', 'excluded')
downloadbooleantrueDisplay column in CSV download file.
emptybooleanfalseThis denotes whether the column has data or not (for use with intentionally empty columns).
filterbooleantrueDisplay column in filter list.
filterListarrayFilter value list. Example
filterOptions{names, logic, display}With filter options, it's possible to use custom names for the filter fields. Example, custom filter logic Example, and custom rendering. Example
customFilterListRenderfunctionFunction that returns a string used as the chip label. function(value) => string Example
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.
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
sortbooleantrueEnable/disable sorting on column.
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
  tableState: {
    announceText: null|string,
    page: number,
    rowsPerPage: number,
    filterList: array,
    selectedRows: {
      data: array,
      lookup: object,
    },
    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. 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 MuiDt from "mui-dt";
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()}>
        <MuiDt 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",
    },
    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",
    },
  }
  ...
}

Breaking Changes with mui-datatables

This library started as a fork of mui-datatables. Below I list breaking changes with mui-datatables.

  • The table now retains internal state through re-renders. When you override a table option or column option you take control, but if you opt not to control an option the table will maintain the state and not reset it when the table re-renders.
  • The "resetFilters" event that occurs for the onTableChange function is now called "clearFilters".
  • The responsiveScrollMaxHeight responsiveScrollFullHeight classes on MUIDataTable have been removed.
  • customToolbarSelect renamed customSelectToolbar.
  • disableToolbarSelect renamed disableSelectToolbar.
  • onRowsSelect renamed onRowSelectionChange.
  • onRowsExpand renamed onRowExpansionChange.
  • onFilterChange now takes the column index instead of the column name.
  • responsive option is now "displayMode". "stacked" mode is not tied to smaller screens, instead "responsiveStacked" should be used for this behavior.
  • customHeadRender function signature changed.
  • sortDirection property removed from Column API. Sorting is now handled via a sortOrder property on the options object.

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.

0.11.0

4 years ago

0.10.0

5 years ago

0.9.0

5 years ago

0.8.3

5 years ago

0.8.2

5 years ago

0.8.1

5 years ago

0.8.0

5 years ago

0.7.2

5 years ago

0.7.1

5 years ago

0.7.0

5 years ago

0.6.0

5 years ago

0.5.1

5 years ago

0.5.0

5 years ago

0.4.0

5 years ago

0.3.1

5 years ago

0.3.0

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.1

5 years ago

0.1.0

5 years ago