### Install Dependencies and Run Dev Server
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Install project dependencies and start the development server. Open http://localhost:5050/ in your browser after starting.
```sh
npm i
npm run dev
```
--------------------------------
### Install MUI-Datatables
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Install the mui-datatables package using npm.
```bash
npm install mui-datatables --save
```
--------------------------------
### Install MUI v5 Dependencies
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
If not already present, install Material-UI v5 and its icon pack.
```bash
npm --save install @mui/material @emotion/react @emotion/styled @mui/icons-material
```
--------------------------------
### Full Usage Example with Custom Footer and Callbacks
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablefooter.md
A comprehensive example demonstrating the integration of pagination, custom table body footer rendering, and custom footer component for pagination controls. It also includes `onChangePage` and `onChangeRowsPerPage` callbacks.
```javascript
import React, { useState } from 'react';
import MUIDataTable from 'mui-datatables';
const columns = [
'Name',
'Email',
'Department',
'Salary',
];
const data = [
['John Doe', 'john@example.com', 'Engineering', '$120,000'],
['Jane Smith', 'jane@example.com', 'Sales', '$95,000'],
['Bob Johnson', 'bob@example.com', 'HR', '$85,000'],
// ... more rows
];
const options = {
pagination: true,
rowsPerPage: 10,
rowsPerPageOptions: [5, 10, 25, 50, 100],
jumpToPage: true,
// Custom footer with summary
customTableBodyFooterRender: () => (
),
logic: (row, filters, index) => {
const salary = row[index];
const [min, max] = filters;
if (!min && !max) return true;
if (min && salary < min) return false;
if (max && salary > max) return false;
return true;
}
}
}
},
];
const data = [
['John Doe', 'Engineering', 120000],
['Jane Smith', 'Sales', 95000],
['Bob Johnson', 'HR', 85000],
];
const options = {
filterType: 'checkbox',
confirmFilters: false,
onFilterChange: (changedColumn, filterList, type, changedIndex, displayData) => {
console.log('Filters changed:', changedColumn, filterList);
},
};
export default function Table() {
return (
);
}
```
--------------------------------
### MUI-Datatables Usage Example with Custom Chips and Callbacks
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablefilterlist.md
This example demonstrates a full MUI-Datatables implementation, including custom filter chip rendering, custom styling based on column, and handling filter chip closures.
```javascript
import React, { useState } from 'react';
import MUIDataTable from 'mui-datatables';
import Chip from '@mui/material/Chip';
// Custom chip component
const CustomChip = ({ label, onDelete, variant = 'default', color = 'default' }) => (
);
const columns = [
{
name: 'name',
label: 'Name',
options: {
filter: true,
customFilterListOptions: {
render: (value) => value.map(v => `Name: ${v}`),
}
}
},
{
name: 'department',
label: 'Department',
options: {
filter: true,
customFilterListOptions: {
render: (value) => value.map(v => `Dept: ${v}`),
}
}
},
{
name: 'status',
label: 'Status',
options: {
filter: true,
customFilterListOptions: {
render: (value) => value.map(v => `Status: ${v}`),
}
}
},
];
const data = [
['John Doe', 'Engineering', 'Active'],
['Jane Smith', 'Sales', 'Active'],
['Bob Johnson', 'HR', 'Inactive'],
];
const options = {
filter: true,
filterType: 'checkbox',
components: {
// Use custom chip component
TableFilterList: (props) => (
),
},
setFilterChipProps: (colIndex, colName, filterValue) => {
// Customize chip styling based on column
const colorMap = {
0: 'primary', // name column - blue
1: 'secondary', // department column - pink
2: 'default', // status column - default
};
return {
color: colorMap[colIndex],
variant: 'outlined',
};
},
onFilterChipClose: (index, removedFilter, filterList) => {
console.log(`Removed filter from column ${index}:`, removedFilter);
console.log('Updated filter list:', filterList);
},
};
export default function Table() {
const [filterList, setFilterList] = useState([]);
return (
{
setFilterList(filterList);
console.log('Filter changed:', changedColumn, filterList);
},
}}
/>
);
}
```
--------------------------------
### MUIDataTable with Server-Side and Storage
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/utilities.md
Example of setting up MUIDataTable with server-side processing enabled and a storage key for persisting table state to localStorage. Includes a custom search render with debouncing.
```javascript
import MUIDataTable, {
debounceSearchRender,
DebounceTableSearch,
} from 'mui-datatables';
const columns = ['Name', 'Email', 'Status'];
const data = [
['John', 'john@example.com', 'Active'],
['Jane', 'jane@example.com', 'Active'],
['Bob', 'bob@example.com', 'Inactive'],
];
const options = {
// Use debounced search for server-side
serverSide: true,
customSearchRender: debounceSearchRender(300),
// Persist state to localStorage
storageKey: 'employees_table',
onTableChange: (action, tableState) => {
console.log('Table changed:', action);
},
};
export default function Table() {
return (
);
}
```
--------------------------------
### Custom Filter Logic Example
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Demonstrates how to implement custom filter logic for a column. This is useful when the default filtering mechanisms are insufficient.
```javascript
logic: (val, search) => {
// custom logic here
return val.toLowerCase().includes(search.toLowerCase());
}
```
--------------------------------
### MUI-Datatables Basic Usage with Options
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tabletoolbar.md
A complete example demonstrating how to set up MUI-Datatables with columns, data, and various options including search, filtering, printing, downloading, and custom download logic.
```javascript
import React from 'react';
import MUIDataTable from 'mui-datatables';
const columns = [
{
name: 'name',
label: 'Name',
options: { searchable: true }
},
{
name: 'status',
label: 'Status',
options: {
filter: true,
filterType: 'dropdown',
filterOptions: {
names: ['Active', 'Inactive', 'Pending']
}
}
},
];
const data = [
['John Doe', 'Active'],
['Jane Smith', 'Inactive'],
['Bob Johnson', 'Pending'],
];
const options = {
search: true,
filter: true,
print: true,
download: true,
viewColumns: true,
downloadOptions: {
filename: 'table_data.csv',
separator: ',',
},
onDownload: (buildHead, buildBody, columns, data) => {
// Custom download logic
return buildHead(columns) + buildBody(data);
},
};
export default function Table() {
return (
);
}
```
--------------------------------
### Basic MUI-Datatables Usage
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/README.md
Demonstrates the fundamental setup of MUIDataTable with simple column and data arrays, and basic options. Ensure React and MUIDataTable are imported.
```javascript
import React from 'react';
import MUIDataTable from 'mui-datatables';
const columns = ['Name', 'Email', 'Department'];
const data = [
['John Doe', 'john@example.com', 'Engineering'],
['Jane Smith', 'jane@example.com', 'Sales'],
['Bob Johnson', 'bob@example.com', 'HR'],
];
const options = {
filterType: 'checkbox',
};
export default function Table() {
return (
);
}
```
--------------------------------
### Custom Footer Rendering
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablefooter.md
Demonstrates how to render a custom footer for the table body, for example, to display a summary of the data.
```APIDOC
## customTableBodyFooterRender
### Description
Allows you to provide a custom render function for the table body footer. This is useful for displaying summary information or other custom content at the bottom of the table body.
### Parameters
This option accepts a function that returns a React node.
### Usage Example
```javascript
const options = {
customTableBodyFooterRender: () => (
Total Employees: {data.length}
),
};
```
```
--------------------------------
### Custom Header Cell Props Example
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Provides an example of how to set custom properties for header cells based on column metadata. This allows for dynamic styling or behavior of table headers.
```javascript
setCellHeaderProps: (columnMeta) => {
return {
style: {
backgroundColor: "#f0f0f0",
color: "#333",
fontWeight: "bold"
}
};
}
```
--------------------------------
### Responsive Table Configuration
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/advanced-patterns.md
Configure table responsiveness based on window width. This example sets different `selectableRows` modes and dynamically hides columns defined in `hideOnMobile` for screens smaller than 768px.
```javascript
const options = {
responsive: 'standard',
tableBodyHeight: '600px',
tableBodyMaxHeight: '600px',
rowsPerPage: 10,
rowsPerPageOptions: [5, 10, 25],
// Mobile-specific
selectableRows: window.innerWidth < 768 ? 'single' : 'multiple',
// Hide columns on mobile
columns: columns.map(col => ({
...col,
options: {
...col.options,
display: window.innerWidth < 768 && hideOnMobile.includes(col.name)
? 'excluded'
: true,
},
})),
};
```
--------------------------------
### Custom Filter Rendering Example
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Shows how to provide a custom rendering function for the filter dialog of a column. This allows for completely custom filter UI elements.
```javascript
display: (filterList, onChange, index, column) => {
return (
Custom Filter Title onChange(event.target.value, index, column)}
/>
);
}
```
--------------------------------
### Basic Usage Example with Expandable Rows
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/expandbutton.md
Demonstrates how to enable expandable rows and define a custom component to render the content of an expanded row. The `expandableRowsOnClick` option is set to false to ensure expansion only occurs via the button.
```javascript
import React from 'react';
import MUIDataTable from 'mui-datatables';
const columns = [
'Name',
'Email',
'Department',
];
const data = [
['John Doe', 'john@example.com', 'Engineering'],
['Jane Smith', 'jane@example.com', 'Sales'],
['Bob Johnson', 'bob@example.com', 'HR'],
];
const options = {
expandableRows: true,
expandableRowsOnClick: false, // Expand via button only
renderExpandableRow: (rowData, rowMeta) => (
Details for {rowData[0]}
Email: {rowData[1]}
Department: {rowData[2]}
Row Index: {rowMeta.dataIndex}
),
onRowExpansionChange: (currentRowsExpanded, allRowsExpanded, rowsExpanded) => {
console.log('Expanded rows:', currentRowsExpanded);
},
};
export default function Table() {
return (
);
}
```
--------------------------------
### Custom Sort Function Example
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Shows how to define a custom sorting function for a column. This function takes an order string and returns a comparator function for custom sorting logic.
```javascript
sortCompare: (order) => (a, b) => {
// Custom comparison logic based on order ('asc' or 'desc')
if (order === "asc") {
return a.data < b.data ? -1 : a.data > b.data ? 1 : 0;
} else {
return a.data > b.data ? -1 : a.data < b.data ? 1 : 0;
}
}
```
--------------------------------
### Disable Pagination Configuration
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablefooter.md
Example of how to disable pagination entirely, which will display all rows.
```APIDOC
## Disable Pagination
```javascript
const options = {
pagination: false,
// Shows all rows in table
};
```
```
--------------------------------
### Server-Side Integration with Debounced Search
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/debouncetablesearch.md
This example demonstrates a comprehensive server-side integration using debounced search. It handles data fetching, pagination, and row count updates, with a 300ms debounce delay for search queries.
```javascript
import MUIDataTable, { debounceSearchRender } from 'mui-datatables';
import { useState } from 'react';
const ServerSideSearchTable = () => {
const [data, setData] = useState([]);
const [count, setCount] = useState(0);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const [searchText, setSearchText] = useState('');
const columns = [
'Name',
'Email',
'Position',
];
const fetchData = async (search, pageNum, pageSize) => {
try {
const response = await fetch(
`/api/employees?search=${encodeURIComponent(search)}&page=${pageNum}&limit=${pageSize}`
);
const result = await response.json();
setData(result.data);
setCount(result.total);
} catch (error) {
console.error('Fetch error:', error);
}
};
const options = {
serverSide: true,
count: count,
page: page,
rowsPerPage: rowsPerPage,
// Debounced search with 300ms delay
customSearchRender: debounceSearchRender(300),
// Handle search input with debounce
onSearchChange: (searchText) => {
setSearchText(searchText);
setPage(0); // Reset to first page
fetchData(searchText, 0, rowsPerPage);
},
// Handle pagination
onChangePage: (newPage) => {
setPage(newPage);
fetchData(searchText, newPage, rowsPerPage);
},
onChangeRowsPerPage: (newRowsPerPage) => {
setRowsPerPage(newRowsPerPage);
setPage(0);
fetchData(searchText, 0, newRowsPerPage);
},
onTableChange: (action, tableState) => {
console.log('Table action:', action);
},
};
return (
);
};
export default ServerSideSearchTable;
```
--------------------------------
### Custom Row Rendering Example
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablebody.md
Override the entire row rendering logic. This is useful for complex row structures or when custom layouts are needed.
```javascript
const options = {
customRowRender: (data, dataIndex, rowIndex) => {
// data: row data array
// dataIndex: index in original data array
// rowIndex: index in current display
return (
Custom row content for {data[0]}
);
},
};
```
--------------------------------
### Server-Side Search Implementation
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablesearch.md
This example demonstrates how to set up MUI-datatables for server-side searching. It utilizes the `serverSide` option and `onTableChange` to trigger data fetching from an API endpoint with a debounced search input. Ensure your API endpoint `/api/employees` is configured to handle search queries.
```javascript
import React, { useState } from 'react';
import MUIDataTable from 'mui-datatables';
import { debounceSearchRender } from 'mui-datatables';
const columns = ['Name', 'Email', 'Department'];
const ServerSideSearchTable = () => {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const fetchData = (searchText) => {
setLoading(true);
// Fetch from server with search query
fetch(`/api/employees?search=${encodeURIComponent(searchText)}`)
.then(res => res.json())
.then(result => {
setData(result.data);
setLoading(false);
});
};
const options = {
serverSide: true,
searchAlwaysOpen: false,
customSearchRender: debounceSearchRender(500), // 500ms debounce
onTableChange: (action, tableState) => {
if (action === 'search') {
fetchData(tableState.searchText || '');
}
},
};
return (
);
};
export default ServerSideSearchTable;
```
--------------------------------
### Custom Text Labels Configuration
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablepagination.md
Example showing how to customize the text labels used in the pagination component, such as for next/previous buttons, rows per page selector, and jump-to-page input.
```APIDOC
## Custom Text Labels
```javascript
const options = {
textLabels: {
pagination: {
next: 'Next →',
previous: '← Previous',
rowsPerPage: 'Show:',
displayRows: 'of',
jumpToPage: 'Go to:',
},
},
};
```
```
--------------------------------
### Server-Side Pagination Example
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablefooter.md
This component fetches data from an API based on the current page and rows per page, and configures MUIDataTable to use server-side pagination. It manages state for data, total count, current page, and rows per page.
```javascript
import React, { useState, useEffect } from 'react';
import MUIDataTable from 'mui-datatables';
const ServerSidePaginationTable = () => {
const [data, setData] = useState([]);
const [count, setCount] = useState(0);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const [loading, setLoading] = useState(false);
useEffect(() => {
fetchData();
}, [page, rowsPerPage]);
const fetchData = async () => {
setLoading(true);
const response = await fetch(
`/api/employees?page=${page}&limit=${rowsPerPage}`
);
const result = await response.json();
setData(result.data);
setCount(result.total);
setLoading(false);
};
const options = {
serverSide: true,
count: count,
page: page,
rowsPerPage: rowsPerPage,
onChangePage: (newPage) => setPage(newPage),
onChangeRowsPerPage: (newRowsPerPage) => {
setRowsPerPage(newRowsPerPage);
setPage(0);
},
};
return (
);
};
export default ServerSidePaginationTable;
```
--------------------------------
### Basic MUI-Datatables Usage with Column Options
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tableviewcol.md
Demonstrates a typical MUI-Datatables setup with various column definitions, including options for display, filtering, and search. Use `display: 'excluded'` for columns that should never be visible to the user.
```javascript
import React, { useState } from 'react';
import MUIDataTable from 'mui-datatables';
const columns = [
{
name: 'id',
label: 'ID',
options: {
display: 'excluded', // Never visible to user
filter: false,
search: false,
},
},
{
name: 'name',
label: 'Name',
options: {
display: true,
filter: true,
},
},
{
name: 'email',
label: 'Email',
options: {
display: true,
filter: true,
},
},
{
name: 'phone',
label: 'Phone',
options: {
display: false, // Hidden by default
filter: true,
viewColumns: true, // User can toggle it
},
},
{
name: 'internalNotes',
label: 'Internal Notes',
options: {
display: 'excluded', // Hidden from users
download: false,
},
},
{
name: 'company',
label: 'Company',
options: {
display: true,
filter: true,
},
},
];
const data = [
[1, 'John Doe', 'john@example.com', '555-1234', 'Internal note 1', 'Acme Corp'],
[2, 'Jane Smith', 'jane@example.com', '555-5678', 'Internal note 2', 'TechCorp'],
[3, 'Bob Johnson', 'bob@example.com', '555-9012', 'Internal note 3', 'StartupX'],
];
const options = {
viewColumns: true,
storageKey: 'employee_table',
onViewColumnsChange: (changedColumn, action) => {
console.log(`Column "${changedColumn}" was ${action}`);
},
};
export default function Table() {
return (
);
}
```
--------------------------------
### Basic MUI-Datatable Integration
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/muidatatable.md
This snippet demonstrates a standard setup for MUI-Datatable, including column definitions with filtering and sorting, sample data, and basic table options like filter type and row selection. It also shows how to implement custom rendering for a status column and expandable rows.
```javascript
import React from 'react';
import MUIDataTable from 'mui-datatables';
const columns = [
{
name: 'name',
label: 'Name',
options: {
filter: true,
sort: true,
},
},
{
name: 'email',
label: 'Email',
options: {
filter: true,
},
},
{
name: 'status',
label: 'Status',
options: {
customBodyRender: (value) => (
{value}
),
},
},
];
const data = [
{ name: 'John Doe', email: 'john@example.com', status: 'active' },
{ name: 'Jane Smith', email: 'jane@example.com', status: 'inactive' },
{ name: 'Bob Johnson', email: 'bob@example.com', status: 'active' },
];
const options = {
filterType: 'checkbox',
selectableRows: 'multiple',
expandableRows: true,
renderExpandableRow: (rowData, rowMeta) => (
Additional details for {rowData[0]}
),
onTableChange: (action, tableState) => {
console.log(action, tableState);
},
};
export default function Table() {
return (
);
}
```
--------------------------------
### Customize MUI-Datatables Theme
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/advanced-patterns.md
This example demonstrates how to create a custom Material-UI theme to override styles for MUIDataTable components, including table headers and cells. Import `createTheme` and `ThemeProvider` from `@mui/material/styles`.
```javascript
import { createTheme, ThemeProvider } from '@mui/material/styles';
const theme = createTheme({
components: {
MUIDataTable: {
styleOverrides: {
root: {
'& thead': {
backgroundColor: '#f5f5f5',
},
},
},
},
MuiTableCell: {
styleOverrides: {
head: {
fontWeight: 'bold',
backgroundColor: '#e0e0e0',
},
},
},
MuiTableRow: {
styleOverrides: {
root: {
'&:hover': {
backgroundColor: '#f9f9f9',
},
},
},
},
},
});
export default function App() {
return (
);
}
```
--------------------------------
### MUI-Datatables with Debounced Search
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/utilities.md
Example of integrating debounceSearchRender into MUIDataTable options for server-side searching. This configuration debounces search requests to the server.
```javascript
import MUIDataTable, { debounceSearchRender } from 'mui-datatables';
const options = {
serverSide: true,
customSearchRender: debounceSearchRender(500),
onTableChange: (action, tableState) => {
if (action === 'search') {
fetchDataFromServer(tableState.searchText);
}
},
};
```
--------------------------------
### Column Definition Examples
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/muidatatable.md
Columns can be defined as simple strings for basic display or as objects with detailed options for advanced control over filtering, sorting, and display.
```javascript
// Simple string column
"Name"
```
```javascript
// Object with options
{
name: "name", // Required: field name
label: "Full Name", // Display label (defaults to name)
options: {
filter: true, // Include in filters
sort: true, // Allow sorting
display: true, // Display column
download: true, // Include in CSV export
searchable: true, // Include in search
print: true, // Include when printing
viewColumns: true, // Allow hide/show
draggable: true, // Allow column dragging
customBodyRender: (value, tableMeta, updateValue) => { },
customHeadRender: (columnMeta, handleToggleColumn, sortOrder) => { },
}
}
```
--------------------------------
### Define Column with Options
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Use the 'options' property within a column definition to customize its behavior and appearance. This example shows how to enable filtering and disable sorting for a 'Name' column.
```javascript
const columns = [
{
name: "Name",
options: {
filter: true,
sort: false
}
},
...
];
```
--------------------------------
### Debounced Search Render for Server-Side
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablesearch.md
Integrate server-side searching with a debounce mechanism to limit the rate of search requests. This example uses a 300ms debounce delay.
```javascript
import { debounceSearchRender } from 'mui-datatables';
const options = {
serverSide: true,
customSearchRender: debounceSearchRender(300), // 300ms debounce
onTableChange: (action, tableState) => {
if (action === 'changePage' || action === 'changeRowsPerPage') {
// Handle pagination
} else if (action === 'search') {
// Fetch data with tableState.searchText
fetchRemoteData(tableState.searchText);
}
},
};
```
--------------------------------
### Custom Filter Value Rendering Example
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Illustrates how to customize the display of filter choices within the filter dialog. This is useful for transforming how filter options are presented, such as displaying '(empty)' for null values.
```javascript
renderValue: (val) => {
if (val === '') return "(empty)";
return val;
}
```
--------------------------------
### Basic Debounced Search Implementation
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/debouncetablesearch.md
Use `debounceSearchRender` with a specified debounce time (e.g., 500ms) to automatically debounce search input. This example shows integration with server-side data fetching triggered by the search action.
```javascript
import MUIDataTable, { debounceSearchRender } from 'mui-datatables';
const columns = ['Name', 'Email', 'Department'];
const options = {
serverSide: true,
customSearchRender: debounceSearchRender(500), // 500ms debounce
onTableChange: (action, tableState) => {
if (action === 'search') {
fetchDataFromServer(tableState.searchText);
}
},
};
export default function Table() {
const [data, setData] = useState([]);
const fetchDataFromServer = (searchText) => {
fetch(`/api/search?q=${encodeURIComponent(searchText)}`)
.then(res => res.json())
.then(result => setData(result.data));
};
return (
);
}
```
--------------------------------
### Custom Body Cell Props Example
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Demonstrates how to apply custom properties to individual data cells based on their value, row index, and column index. This enables conditional styling or behavior for cells.
```javascript
setCellProps: (cellValue, rowIndex, columnIndex) => {
if (columnIndex === 2 && cellValue < 50) {
return {
style: {
backgroundColor: "#ffcccc",
color: "#cc0000"
}
};
}
return {};
}
```
--------------------------------
### Run Test Suite
Source: https://github.com/gregnb/mui-datatables/blob/master/README.md
Execute the project's test suite to ensure changes do not break existing functionality.
```sh
npm test
```
--------------------------------
### Jump to Page Configuration
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablepagination.md
Demonstrates how to enable the 'jump to page' input functionality within the pagination controls by setting the `jumpToPage` option to `true`.
```APIDOC
## Jump to Page
Add jump-to-page input:
```javascript
const options = {
jumpToPage: true,
pagination: true,
};
```
```
--------------------------------
### Get Default Text Labels
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/utilities.md
Retrieves the default localized text labels for the table. Use this to customize specific labels while retaining others.
```javascript
import MUIDataTable from 'mui-datatables';
function getTextLabels(): TextLabels
```
```javascript
import MUIDataTable from 'mui-datatables';
// Get default labels
const defaultLabels = MUIDataTable.getTextLabels?.() || {};
const options = {
textLabels: {
...defaultLabels,
toolbar: {
...defaultLabels.toolbar,
search: 'Find Records',
},
},
};
```
--------------------------------
### Basic Pagination Configuration
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablepagination.md
Configure basic pagination with the 'pagination' and 'rowsPerPage' options. 'rowsPerPageOptions' allows customization of the dropdown choices.
```javascript
const options = {
pagination: true,
rowsPerPage: 10,
rowsPerPageOptions: [5, 10, 25, 50, 100],
};
```
--------------------------------
### Integration with Download and Print
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tableviewcol.md
Illustrates how column visibility settings for the table view are independent of their visibility in download and print functionalities.
```APIDOC
## Integration with Download and Print
Column visibility is independent from download/print visibility:
```javascript
const columns = [
{
name: 'email',
label: 'Email',
options: {
display: true, // Show in table
download: false, // Exclude from CSV download
print: false, // Exclude from print
},
},
];
```
```
--------------------------------
### Custom Cell Rendering for Status
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/README.md
Customize the appearance of cells in a specific column using `customBodyRender`. This example shows how to style a 'status' cell based on its value.
```javascript
{
name: 'status',
label: 'Status',
options: {
customBodyRender: (value) => (
{value}
),
},
}
```
--------------------------------
### Basic Table Search Configuration
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablesearch.md
Demonstrates how to enable and configure basic search functionality for a MUI-datatables table. Includes options for case sensitivity, search placeholder, and search input properties.
```javascript
import React, { useState } from 'react';
import MUIDataTable from 'mui-datatables';
import { debounceSearchRender } from 'mui-datatables';
const columns = [
{
name: 'name',
label: 'Name',
options: {
searchable: true, // Include in search
}
},
{
name: 'email',
label: 'Email',
options: {
searchable: true,
}
},
{
name: 'internalId',
label: 'ID',
options: {
searchable: false, // Exclude from search
}
},
];
const data = [
['John Doe', 'john@example.com', '12345'],
['Jane Smith', 'jane@example.com', '67890'],
['Bob Johnson', 'bob@example.com', '11111'],
];
const options = {
// Basic search
search: true,
caseSensitive: false,
searchPlaceholder: 'Search by name or email...',
searchProps: {
autoComplete: 'off',
},
// Callback when search changes
onSearchChange: (searchText) => {
console.log('Search text changed:', searchText);
},
// Callback when search opens/closes
onSearchOpen: () => console.log('Search opened'),
onSearchClose: () => console.log('Search closed'),
// Custom search logic
customSearch: (searchQuery, currentRow, columns) => {
// Example: search only name and email, ignore case
const name = String(currentRow[0]).toLowerCase();
const email = String(currentRow[1]).toLowerCase();
const query = searchQuery.toLowerCase();
return name.includes(query) || email.includes(query);
},
};
export default function Table() {
return (
);
}
```
--------------------------------
### Filter List Structure Example
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tablefilterlist.md
The filterList prop is an array where each index corresponds to a column, defining the filters to be applied to that column. Empty arrays indicate no filters for a column.
```javascript
filterList = [
[], // Column 0: no filters
['John', 'Jane'], // Column 1: multiple filters
['2023-01-01'], // Column 2: single date filter
[], // Column 3: no filters
]
```
--------------------------------
### Column Visibility Options
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/tableviewcol.md
Demonstrates the different 'display' option values for controlling column visibility within column definitions.
```javascript
{
name: 'email',
label: 'Email',
options: {
display: true, // Visible and toggleable
// or
display: false, // Hidden but toggleable
// or
display: 'excluded', // Hidden, not toggleable
// or
display: 'always', // Always visible, not toggleable
}
}
```
--------------------------------
### Custom Debounced Search Component
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/api-reference/debouncetablesearch.md
Integrate a custom search component by providing a `customSearchRender` function. This example uses `DebounceTableSearch` to create a customizable debounced search input within the table.
```javascript
import React from 'react';
import MUIDataTable from 'mui-datatables';
import { DebounceTableSearch } from 'mui-datatables';
const CustomSearchTable = () => {
const columns = ['Name', 'Email', 'Company'];
const options = {
customSearchRender: (searchText, handleSearch, hideSearch, options) => (
),
};
return (
);
};
```
--------------------------------
### Get Locale-Aware Comparator
Source: https://github.com/gregnb/mui-datatables/blob/master/_autodocs/utilities.md
Provides a comparator function for sorting strings that correctly handles accents, diacritics, and numeric sorting using Intl.Collator. Falls back to localeCompare if Intl is unavailable.
```javascript
function getCollatorComparator(): (a: string, b: string) => number
```
```javascript
const comparator = getCollatorComparator();
const sorted = stringArray.sort(comparator);
```