### Full Simple Example with Material React Table Source: https://www.material-react-table.com/docs/getting-started/usage Demonstrates a complete setup for a Material React Table, including data, column definitions with TypeScript, and table options. Ensure data and columns are memoized or stable to prevent performance issues. ```javascript import { useMemo } from 'react'; import { MaterialReactTable, useMaterialReactTable, type MRT_ColumnDef, //if using TypeScript (optional, but recommended) } from 'material-react-table'; //If using TypeScript, define the shape of your data (optional, but recommended) interface Person { name: string; age: number; } //mock data - strongly typed if you are using TypeScript (optional, but recommended) const data: Person[] = [ { name: 'John', age: 30, }, { name: 'Sara', age: 25, }, ]; export default function App() { //column definitions - strongly typed if you are using TypeScript (optional, but recommended) const columns = useMemo[]>( () => [ { accessorKey: 'name', //simple recommended way to define a column header: 'Name', muiTableHeadCellProps: { style: { color: 'green' } }, //custom props enableHiding: false, //disable a feature for this column }, { accessorFn: (originalRow) => parseInt(originalRow.age), id: 'age', //id required if you use accessorFn instead of accessorKey header: 'Age', Header: Age, //optional custom markup Cell: ({ cell }) => {cell.getValue().toLocaleString()}, //optional custom cell render }, ], [], ); //pass table options to useMaterialReactTable const table = useMaterialReactTable({ columns, data, //must be memoized or stable (useState, useMemo, defined outside of this component, etc.) enableRowSelection: true, //enable some features enableColumnOrdering: true, //enable a feature for all columns enableGlobalFilter: false, //turn off a feature }); //note: you can also pass table options as props directly to instead of using useMaterialReactTable //but the useMaterialReactTable hook will be the most recommended way to define table options return ; } ``` -------------------------------- ### Virtualized Table with Large Data Source: https://www.material-react-table.com/docs/examples/virtualized This example shows how to enable row and column virtualization to efficiently render a table with 10,000 rows. It includes setup for data generation, sorting, and optional customization of virtualizer options. ```typescript import { useEffect, useMemo, useRef, useState } from 'react'; import { MaterialReactTable, useMaterialReactTable, type MRT_ColumnDef, type MRT_SortingState, type MRT_RowVirtualizer, } from 'material-react-table'; import { makeData, type Person } from './makeData'; const Example = () => { const columns = useMemo[]>( //column definitions... () => [ { accessorKey: 'firstName', header: 'First Name', size: 150, }, { accessorKey: 'middleName', header: 'Middle Name', size: 170, }, { accessorKey: 'lastName', header: 'Last Name', size: 150, }, { accessorKey: 'email', header: 'Email Address', size: 300, }, { accessorKey: 'phoneNumber', header: 'Phone Number', size: 250, }, { accessorKey: 'address', header: 'Address', size: 300, }, { accessorKey: 'zipCode', header: 'Zip Code', }, { accessorKey: 'city', header: 'City', size: 220, }, { accessorKey: 'state', header: 'State', }, { accessorKey: 'country', header: 'Country', size: 350, }, { accessorKey: 'petName', header: 'Pet Name', }, { accessorKey: 'age', header: 'Age', }, { accessorKey: 'salary', header: 'Salary', }, { accessorKey: 'dateOfBirth', header: 'Date of Birth', }, { accessorKey: 'dateOfJoining', header: 'Date of Joining', }, { accessorKey: 'isActive', header: 'Is Active', }, ], [], ); //optionally access the underlying virtualizer instance const rowVirtualizerInstanceRef = useRef(null); const [data, setData] = useState([]); const [isLoading, setIsLoading] = useState(true); const [sorting, setSorting] = useState([]); useEffect(() => { if (typeof window !== 'undefined') { setData(makeData(10_000)); setIsLoading(false); } }, []); useEffect(() => { //scroll to the top of the table when the sorting changes try { rowVirtualizerInstanceRef.current?.scrollToIndex?.(0); } catch (error) { console.error(error); } }, [sorting]); const table = useMaterialReactTable({ columns, data, //10,000 rows defaultDisplayColumn: { enableResizing: true }, enableBottomToolbar: false, enableColumnResizing: true, enableColumnVirtualization: true, enableGlobalFilterModes: true, enablePagination: false, enableColumnPinning: true, enableRowNumbers: true, enableRowVirtualization: true, muiTableContainerProps: { sx: { maxHeight: '600px' } }, onSortingChange: setSorting, state: { isLoading, sorting }, rowVirtualizerInstanceRef, //optional rowVirtualizerOptions: { overscan: 5 }, //optionally customize the row virtualizer columnVirtualizerOptions: { overscan: 2 }, //optionally customize the column virtualizer }); return ; }; export default Example; ``` -------------------------------- ### React Query Setup with Devtools Source: https://www.material-react-table.com/docs/examples/editing-crud-inline-cell This code demonstrates the basic setup for React Query in an application. It includes configuring the QueryClientProvider and lazily loading the React Query Devtools for production environments. Ensure this setup is at the root of your application for global state management. ```typescript const ReactQueryDevtoolsProduction = lazy(() => import('@tanstack/react-query-devtools/build/modern/production.js').then( (d) => ({ default: d.ReactQueryDevtools, }), ), ); const queryClient = new QueryClient(); export default function App() { return ( ); } ``` -------------------------------- ### Quick Install Material React Table Source: https://www.material-react-table.com/docs/getting-started/install Use this command for a quick installation of Material React Table. Ensure your project meets the compatibility requirements for React, Material UI, and other dependencies. ```bash $ npm i material-react-table ``` -------------------------------- ### Full Example with Custom Cell Actions Source: https://www.material-react-table.com/docs/guides/cell-actions A complete example demonstrating the use of Material React Table with enabled cell actions and custom menu items. ```typescript import { useMemo } from 'react'; import { MaterialReactTable, MRT_ActionMenuItem, useMaterialReactTable, type MRT_ColumnDef, } from 'material-react-table'; import { data, type Person } from './makeData'; import { Divider } from '@mui/material'; import EmailIcon from '@mui/icons-material/Email'; import PersonOffOutlinedIcon from '@mui/icons-material/PersonOffOutlined'; export const Example = () => { const columns = useMemo[]> //column definitions... (() => [ { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'lastName', header: 'Last Name', }, { accessorKey: 'address', header: 'Address', }, { accessorKey: 'city', header: 'City', }, { accessorKey: 'state', header: 'State', }, ], []) const table = useMaterialReactTable({ columns, data, enableCellActions: true, enableClickToCopy: 'context-menu', enableEditing: true, editDisplayMode: 'cell', renderCellActionMenuItems: ({ closeMenu, table, internalMenuItems }) => [ ...internalMenuItems, , } key={1} label="Item 1" onClick={() => { closeMenu(); }} table={table} />, } key={2} label="Item 2" onClick={() => { closeMenu(); }} table={table} />, ], }); return ; }; export default Example; ``` -------------------------------- ### Basic Detail Panel Example Source: https://www.material-react-table.com/docs/guides/detail-panel This example demonstrates how to render a basic detail panel that displays address and location information for each row. It utilizes the `renderDetailPanel` prop and MUI's `useMediaQuery` hook for responsive adjustments. Ensure you have the necessary Person type and makeData function imported. ```typescript import { useMemo } from 'react'; import { MaterialReactTable, useMaterialReactTable, type MRT_ColumnDef, } from 'material-react-table'; import { Box, Typography, useMediaQuery } from '@mui/material'; import { data, type Person } from './makeData'; const Example = () => { const isMobile = useMediaQuery('(max-width: 720px)'); const columns = useMemo[]>( //column definitions... () => [ { accessorKey: 'id', header: 'ID', size: 50, }, { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'middleName', header: 'Middle Name', }, { accessorKey: 'lastName', header: 'Last Name', }, ], [], ); const table = useMaterialReactTable({ columns, data, // displayColumnDefOptions: { //built-in now in v2.6.0 when positionExpandColumn is 'last' // 'mrt-row-expand': { // muiTableHeadCellProps: { // align: 'right', // }, // muiTableBodyCellProps: { // align: 'right', // }, // }, // }, enableColumnPinning: isMobile, //alternative initialState: { expanded: true, }, state: { columnPinning: isMobile ? { right: ['mrt-row-expand'] } : {}, //alternative }, renderDetailPanel: ({ row }) => ( Address: {row.original.address} City: {row.original.city} State: {row.original.state} Country: {row.original.country} ), positionExpandColumn: 'last', }); return ; }; export default Example; ``` -------------------------------- ### React Query Setup with Lazy Loading Source: https://www.material-react-table.com/docs/examples/lazy-detail-panel This snippet shows the basic setup for TanStack React Query, including creating a `QueryClient` and providing it to the application via `QueryClientProvider`. This is necessary for the `useQuery` hook used in the `DetailPanel` component to function. ```typescript const ReactQueryDevtoolsProduction = lazy(() => import('@tanstack/react-query-devtools/build/modern/production.js').then( (d) => ({ default: d.ReactQueryDevtools, }), ), ); const queryClient = new QueryClient(); export default function App() { return ( ); } ``` -------------------------------- ### React Query Setup for App Source: https://www.material-react-table.com/docs/examples/editing-crud-tree Sets up the QueryClientProvider and React Query Devtools for the application. Ensure this is done at the root of your application. ```tsx import { lazy, Suspense } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; const ReactQueryDevtoolsProduction = lazy(() => import('@tanstack/react-query-devtools/build/modern/production.js').then( (d) => ({ default: d.ReactQueryDevtools, }), ), ); const queryClient = new QueryClient(); export default function App() { return ( ); } ``` -------------------------------- ### Full Detail Panel Example Source: https://www.material-react-table.com/docs/guides/detail-panel This example demonstrates conditional rendering of detail panels, custom expand button rotation, and styling the detail panel's background based on the theme mode. ```typescript import { useMemo } from 'react'; import { MaterialReactTable, useMaterialReactTable, type MRT_ColumnDef, } from 'material-react-table'; import { Box, Typography } from '@mui/material'; import { data, type Person } from './makeData'; const Example = () => { const columns = useMemo[]>( //column definitions... () => [ { accessorKey: 'id', header: 'ID', size: 50, }, { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'middleName', header: 'Middle Name', }, { accessorKey: 'lastName', header: 'Last Name', }, ], [], ); const table = useMaterialReactReactTable({ columns, data, enableExpandAll: false, //disable expand all button muiDetailPanelProps: () => ({ sx: (theme) => ({ backgroundColor: theme.palette.mode === 'dark' ? 'rgba(255,210,244,0.1)' : 'rgba(0,0,0,0.1)', }), }), //custom expand button rotation muiExpandButtonProps: ({ row, table }) => ({ onClick: () => table.setExpanded({ [row.id]: !row.getIsExpanded() }), //only 1 detail panel open at a time sx: { transform: row.getIsExpanded() ? 'rotate(180deg)' : 'rotate(-90deg)', transition: 'transform 0.2s', }, }), //conditionally render detail panel renderDetailPanel: ({ row }) => row.original.address ? ( Address: {row.original.address} City: {row.original.city} State: {row.original.state} Country: {row.original.country} ) : null, }); return ; }; export default Example; ``` -------------------------------- ### Click to Copy Example with Customization Source: https://www.material-react-table.com/docs/guides/click-to-copy A comprehensive example demonstrating how to enable click to copy for specific columns, customize the copy button's appearance with icons and styling, and integrate it within a Material React Table. ```typescript import { useMemo } from 'react'; import { MaterialReactTable, type MRT_ColumnDef } from 'material-react-table'; import { ContentCopy } from '@mui/icons-material'; import { data, type Person } from './makeData'; const Example = () => { const columns = useMemo[]>( () => [ { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'lastName', header: 'Last Name', }, { accessorKey: 'email', header: 'Email', enableClickToCopy: true, muiCopyButtonProps: { fullWidth: true, startIcon: , sx: { justifyContent: 'flex-start' }, }, }, { accessorKey: 'city', header: 'City', enableClickToCopy: true, }, ], [], ); return ; }; export default Example; ``` -------------------------------- ### Install Material React Table with Peer Dependencies Source: https://www.material-react-table.com/docs/getting-started/install This command installs Material React Table along with its essential peer dependencies. It is the recommended installation method to ensure compatibility and avoid potential issues. ```bash $ npm i material-react-table @mui/material @mui/x-date-pickers @mui/icons-material @emotion/react @emotion/styled ``` -------------------------------- ### Render Detail Panel Example Source: https://www.material-react-table.com/docs/api/column-options Demonstrates how to use the `renderDetailPanel` prop to display custom content for each row, conditionally showing a description or a placeholder. ```javascript renderDetailPanel={({ row }) => ( {row.original.description || 'No Description Provided... Yet...'} )} ``` -------------------------------- ### Row Drag and Drop Ordering Example Source: https://www.material-react-table.com/docs/examples/row-ordering This example shows how to enable row ordering using `enableRowOrdering` and handle the drag and drop logic with `muiRowDragHandleProps`. It requires the `useMaterialReactTable` hook and a state to manage the data. ```typescript import { useMemo, useState } from 'react'; import { useMaterialReactTable, type MRT_ColumnDef, type MRT_Row, MRT_TableContainer, } from 'material-react-table'; import { data as initData, type Person } from './makeData'; const Example = () => { const columns = useMemo[]>( //column definitions... () => [ { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'lastName', header: 'Last Name', }, { accessorKey: 'city', header: 'City', }, ], [], ); const [data, setData] = useState(() => initData); const table = useMaterialReactReactTable({ autoResetPageIndex: false, columns, data, enableRowOrdering: true, enableSorting: false, muiRowDragHandleProps: ({ table }) => ({ onDragEnd: () => { const { draggingRow, hoveredRow } = table.getState(); if (hoveredRow && draggingRow) { data.splice( (hoveredRow as MRT_Row).index, 0, data.splice(draggingRow.index, 1)[0], ); setData([...data]); } }, }), }); return ; }; export default Example; ``` -------------------------------- ### React Query Setup in App.tsx Source: https://www.material-react-table.com/docs/examples/editing-crud-inline-table Sets up the QueryClient and QueryClientProvider for React Query. Includes lazy loading for React Query Devtools in production. ```typescript const ReactQueryDevtoolsProduction = lazy(() => import('@tanstack/react-query-devtools/build/modern/production.js').then( (d) => ({ default: d.ReactQueryDevtools, }), ), ); const queryClient = new QueryClient(); export default function App() { return ( ); } ``` -------------------------------- ### Custom Toolbar Example Source: https://www.material-react-table.com/docs/guides/toolbar-customization This example demonstrates how to create a fully custom toolbar for Material React Table, including a 'Create New Account' button, global filter, column toggles, and a print button. It shows how to integrate custom components above and below the table. ```typescript import { MRT_GlobalFilterTextField, MRT_ShowHideColumnsButton, MRT_TablePagination, MRT_ToggleDensePaddingButton, MRT_ToggleFiltersButton, MRT_ToolbarAlertBanner, useMaterialReactTable, type MRT_ColumnDef, MRT_TableContainer, } from 'material-react-table'; import { IconButton, Box, Button, Typography, Tooltip } from '@mui/material'; import PrintIcon from '@mui/icons-material/Print'; import { data, type Person } from './makeData'; const columns: MRT_ColumnDef[] = [ { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'lastName', header: 'Last Name', }, { accessorKey: 'age', header: 'Age', }, { accessorKey: 'salary', header: 'Salary', }, ]; const Example = () => { const table = useMaterialReactTable({ columns, data, enableRowSelection: true, initialState: { showGlobalFilter: true }, }); return ( {/* Our Custom External Top Toolbar * / ({ display: 'flex', backgroundColor: 'inherit', borderRadius: '4px', flexDirection: 'row', gap: '16px', justifyContent: 'space-between', padding: '24px 16px', '@media max-width: 768px': { flexDirection: 'column', }, })} > window.print()}> {/* Some Page Content * / { "Hey I'm some page content. I'm just one of your normal components between your custom toolbar and the MRT Table below" } {/* The MRT Table with no toolbars built-in * / {/* Our Custom Bottom Toolbar * / ); }; export default Example; ``` -------------------------------- ### Infinite Scrolling Example with TanStack React Query Source: https://www.material-react-table.com/docs/examples/infinite-scrolling This example shows a complete implementation of infinite scrolling. It uses `useInfiniteQuery` to fetch data in pages and `fetchMoreOnBottomReached` to trigger fetching more data as the user scrolls. It also includes logic to reset scroll position when sorting or filters change. ```typescript import { lazy, Suspense, type UIEvent, useCallback, useEffect, useMemo, useRef, useState, } from 'react'; import { MaterialReactTable, useMaterialReactTable, type MRT_ColumnDef, type MRT_ColumnFiltersState, type MRT_SortingState, type MRT_RowVirtualizer, } from 'material-react-table'; import { Typography } from '@mui/material'; import { QueryClient, QueryClientProvider, useInfiniteQuery, } from '@tanstack/react-query'; //Note: this is TanStack React Query V5 //Your API response shape will probably be different. Knowing a total row count is important though. type UserApiResponse = { data: Array; meta: { totalRowCount: number; }; }; type User = { firstName: string; lastName: string; address: string; state: string; phoneNumber: string; }; const columns: MRT_ColumnDef[] = [ { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'lastName', header: 'Last Name', }, { accessorKey: 'address', header: 'Address', }, { accessorKey: 'state', header: 'State', }, { accessorKey: 'phoneNumber', header: 'Phone Number', }, ]; const fetchSize = 25; const Example = () => { const tableContainerRef = useRef(null); //we can get access to the underlying TableContainer element and react to its scroll events const rowVirtualizerInstanceRef = useRef(null); //we can get access to the underlying Virtualizer instance and call its scrollToIndex method const [columnFilters, setColumnFilters] = useState( [], ); const [globalFilter, setGlobalFilter] = useState(); const [sorting, setSorting] = useState([]); const { data, fetchNextPage, isError, isFetching, isLoading } = useInfiniteQuery({ queryKey: [ 'users-list', { columnFilters, //refetch when columnFilters changes globalFilter, //refetch when globalFilter changes sorting, //refetch when sorting changes }, ], queryFn: async ({ pageParam }) => { const url = new URL('/api/data', location.origin); // nextjs api route url.searchParams.set('start', `${(pageParam as number) * fetchSize}`); url.searchParams.set('size', `${fetchSize}`); url.searchParams.set('filters', JSON.stringify(columnFilters ?? [])); url.searchParams.set('globalFilter', globalFilter ?? ''); url.searchParams.set('sorting', JSON.stringify(sorting ?? [])); const response = await fetch(url.href); const json = (await response.json()) as UserApiResponse; return json; }, initialPageParam: 0, getNextPageParam: (_lastGroup, groups) => groups.length, refetchOnWindowFocus: false, }); const flatData = useMemo( () => data?.pages.flatMap((page) => page.data) ?? [], [data], ); const totalDBRowCount = data?.pages?.[0]?.meta?.totalRowCount ?? 0; const totalFetched = flatData.length; //called on scroll and possibly on mount to fetch more data as the user scrolls and reaches bottom of table const fetchMoreOnBottomReached = useCallback( (containerRefElement?: HTMLDivElement | null) => { if (containerRefElement) { const { scrollHeight, scrollTop, clientHeight } = containerRefElement; //once the user has scrolled within 400px of the bottom of the table, fetch more data if we can if ( scrollHeight - scrollTop - clientHeight < 400 && !isFetching && totalFetched < totalDBRowCount ) { fetchNextPage(); } } }, [fetchNextPage, isFetching, totalFetched, totalDBRowCount], ); //scroll to top of table when sorting or filters change useEffect(() => { //scroll to the top of the table when the sorting changes try { rowVirtualizerInstanceRef.current?.scrollToIndex?.(0); } catch (error) { console.error(error); } }, [sorting, columnFilters, globalFilter]); //a check on mount to see if the table is already scrolled to the bottom and immediately needs to fetch more data useEffect(() => { fetchMoreOnBottomReached(tableContainerRef.current); }, [fetchMoreOnBottomReached]); const table = useMaterialReactTable({ columns, data: flatData, enablePagination: false, enableRowNumbers: true, enableRowVirtualization: true, manualFiltering: true, manualSorting: true, muiTableContainerProps: { ref: tableContainerRef, sx: { maxHeight: '500px' }, //give the table a height so we can see the scrolling onScroll: (event: UIEvent) => fetchMoreOnBottomReached(event.currentTarget), //add the scroll event listener to the table container }, muiTableHeadCellProps: { sx: () => ({ // a little bit of styling to make the header cells match the body cells background: '#f5f5f5', }), }, onColumnFiltersChange: setColumnFilters, onGlobalFilterChange: setGlobalFilter, onSortingChange: setSorting, state: { columnFilters, globalFilter, sorting }, //custom hooks renderTopToolbarCustomActions: () => ( Infinite Scrolling ), // For Virtualization rowVirtualizerInstanceRef, rowVirtualizerProps: { initialWindowSize: fetchSize * 3, //give it some buffer so we don't fetch too often overscan: fetchSize, rowHeight: 48, //approximate row height //...other options }, }); return ( ); }; export default Example; ``` -------------------------------- ### Static Row Pinning Example Source: https://www.material-react-table.com/docs/examples/static-row-pinning This example shows how to enable static row pinning. Set 'enableRowPinning' to true and configure 'rowPinningDisplayMode' to 'top-and-bottom' for pinning rows to both the top and bottom of the table. 'enableStickyHeader' is also used to keep the header visible. ```typescript import { useMemo } from 'react'; import { MaterialReactTable, useMaterialReactTable, type MRT_ColumnDef, } from 'material-react-table'; import { data, type Person } from './makeData'; const Example = () => { const columns = useMemo[]>( () => [ { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'lastName', header: 'Last Name', }, { accessorKey: 'email', header: 'Email', }, { accessorKey: 'city', header: 'City', }, ], [], ); const table = useMaterialReactTable({ columns, data, enableRowPinning: true, enablePagination: false, enableStickyHeader: true, rowPinningDisplayMode: 'top-and-bottom', getRowId: (row) => row.email, muiTableContainerProps: { sx: { maxHeight: '400px', }, }, }); return ; }; export default Example; ``` -------------------------------- ### Configure Table Options Source: https://www.material-react-table.com/docs/api/table-options Set various table options like column visibility, density, global filter, and sorting. This example shows how to initialize these properties. ```javascript columnVisibility: { description: false }, density: 'compact', showGlobalFilter: true, sorting: [{ id: 'tableOption', desc: false }], ``` -------------------------------- ### Named Export Example Source: https://www.material-react-table.com/docs/getting-started/install Demonstrates the correct way to import MaterialReactTable using named exports, which is required for v2+. ```javascript - import MaterialReactTable from 'material-react-table' + import { MaterialReactTable } from 'material-react-table' ``` -------------------------------- ### React Query Devtools Setup Source: https://www.material-react-table.com/docs/examples/editing-crud-inline-row This code sets up React Query Devtools for development. It uses lazy loading to import the production build of the devtools. ```javascript const ReactQueryDevtoolsProduction = lazy(() => import('@tanstack/react-query-devtools/build/modern/production.js').then( (d) => ({ default: d.ReactQueryDevtools, }), ) ); const queryClient = new QueryClient(); export default function App() { return ( ); } ``` -------------------------------- ### React Query Setup for Data Fetching Source: https://www.material-react-table.com/docs/examples/infinite-scrolling Set up React Query for efficient data fetching and caching. This includes configuring the QueryClient and providing it to the application using QueryClientProvider. ```typescript const ReactQueryDevtoolsProduction = lazy(() => import('@tanstack/react-query-devtools/build/modern/production.js').then( (d) => ({ default: d.ReactQueryDevtools }), ), ); const queryClient = new QueryClient(); export default function App() { return ( ); } ``` -------------------------------- ### MaterialReactTable Integration with React Query Source: https://www.material-react-table.com/docs/examples/dynamic-columns Demonstrates how to integrate MaterialReactTable with React Query for data fetching and state management. Includes setup for React Query Devtools. ```javascript import React, { lazy, Suspense } from 'react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; import Example from './Example'; // Assuming Example component is defined elsewhere const ReactQueryDevtoolsProduction = lazy(() => import('@tanstack/react-query-devtools/build/modern/production.js').then( (d) => ({ default: d.ReactQueryDevtools }), ), ); const queryClient = new QueryClient(); export default function App() { return ( ); } ``` -------------------------------- ### Basic Column Filtering Setup Source: https://www.material-react-table.com/docs/guides/column-filtering Configure columns with various filter variants like 'select' for gender and 'range' for age. Set the columnFilterDisplayMode to 'popover' for a cleaner UI. ```typescript import { useMemo, } from 'react'; import { MaterialReactTable, useMaterialReactTable, type MRT_ColumnDef, } from 'material-react-table'; import { data, type Person } from './makeData'; const Example = () => { const columns = useMemo[]>( () => [ { accessorKey: 'id', header: 'ID', }, { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'lastName', header: 'Last Name', }, { accessorKey: 'gender', header: 'Gender', filterFn: 'equals', filterSelectOptions: ['Male', 'Female', 'Other'], filterVariant: 'select', }, { accessorKey: 'age', header: 'Age', filterVariant: 'range', }, ], [], ); const table = useMaterialReactTable({ columns, data, columnFilterDisplayMode: 'popover', }); return ; }; export default Example; ``` -------------------------------- ### Import MaterialReactTable and useMaterialReactTable Source: https://www.material-react-table.com/docs/getting-started/usage Import the main table component and the hook for defining table options. Ensure you have installed the library and its Material UI dependencies. ```javascript import { MaterialReactTable, useMaterialReactTable, } from 'material-react-table'; ``` -------------------------------- ### Manage Table State for Column Pinning Source: https://www.material-react-table.com/docs/api/table-options Control the table's state, specifically for column pinning. This example shows how to pass the current column pinning configuration to the table. ```javascript state={{ columnPinning }} ``` -------------------------------- ### Minimal Table Setup with MRT_Table Source: https://www.material-react-table.com/docs/examples/minimal Use the MRT_Table sub-component for a lighter-weight table when toolbar features are not required. This example disables sorting, filtering, pagination, and column actions, and customizes the table's appearance. ```typescript import { useMemo } from 'react'; import { MRT_Table, //import alternative sub-component if we do not want toolbars type MRT_ColumnDef, useMaterialReactTable, } from 'material-react-table'; import { data, type Person } from './makeData'; export const Example = () => { const columns = useMemo[]>( //column definitions... () => [ { accessorKey: 'firstName', header: 'First Name', }, { accessorKey: 'lastName', header: 'Last Name', }, { accessorKey: 'address', header: 'Address', }, { accessorKey: 'city', header: 'City', }, { accessorKey: 'state', header: 'State', }, ], [], ); const table = useMaterialReactTable({ columns, data, //data must be memoized or stable (useState, useMemo, defined outside of this component, etc.) enableKeyboardShortcuts: false, enableColumnActions: false, enableColumnFilters: false, enablePagination: false, enableSorting: false, mrtTheme: (theme) => ({ baseBackgroundColor: theme.palette.background.default, //change default background color }), muiTableBodyRowProps: { hover: false }, muiTableProps: { sx: { border: '1px solid rgba(81, 81, 81, .5)', caption: { captionSide: 'top', }, }, }, muiTableHeadCellProps: { sx: { border: '1px solid rgba(81, 81, 81, .5)', fontStyle: 'italic', fontWeight: 'normal', }, }, muiTableBodyCellProps: { sx: { border: '1px solid rgba(81, 81, 81, .5)', }, }, renderCaption: ({ table }) => `Here is a table rendered with the lighter weight MRT_Table sub-component, rendering ${table.getRowModel().rows.length} rows.`, }); //using MRT_Table instead of MaterialReactTable if we do not need any of the toolbar components or features return ; }; export default Example; ``` -------------------------------- ### Customize Copy Buttons Source: https://www.material-react-table.com/docs/guides/click-to-copy Customize the appearance and behavior of the copy buttons using the `muiCopyButtonProps` table or column option. This example sets the button to take full width and adds a custom start icon. ```typescript const table = useMaterialReactTable({ columns, data, enableClickToCopy: true, muiCopyButtonProps: { sx: { width: '100%' }, startIcon: , }, }); ``` -------------------------------- ### Material React Table with CSV Export Source: https://www.material-react-table.com/docs/examples/export-csv This example shows a complete Material React Table setup with buttons to export data in various formats (all data, all rows, page rows, selected rows) to CSV. It utilizes the 'export-to-csv' library for CSV generation and download. ```typescript import { MaterialReactTable, useMaterialReactTable, type MRT_Row, createMRTColumnHelper, } from 'material-react-table'; import { Box, Button } from '@mui/material'; import FileDownloadIcon from '@mui/icons-material/FileDownload'; import { mkConfig, generateCsv, download } from 'export-to-csv'; //or use your library of choice here import { data, type Person } from './makeData'; const columnHelper = createMRTColumnHelper(); const columns = [ columnHelper.accessor('id', { header: 'ID', size: 40, }), columnHelper.accessor('firstName', { header: 'First Name', size: 120, }), columnHelper.accessor('lastName', { header: 'Last Name', size: 120, }), columnHelper.accessor('company', { header: 'Company', size: 300, }), columnHelper.accessor('city', { header: 'City', }), columnHelper.accessor('country', { header: 'Country', size: 220, }), ]; const csvConfig = mkConfig({ fieldSeparator: ',', decimalSeparator: '.', useKeysAsHeaders: true, }); const Example = () => { const handleExportRows = (rows: MRT_Row[]) => { const rowData = rows.map((row) => row.original); const csv = generateCsv(csvConfig)(rowData); download(csvConfig)(csv); }; const handleExportData = () => { const csv = generateCsv(csvConfig)(data); download(csvConfig)(csv); }; const table = useMaterialReactTable({ columns, data, enableRowSelection: true, columnFilterDisplayMode: 'popover', paginationDisplayMode: 'pages', positionToolbarAlertBanner: 'bottom', renderTopToolbarCustomActions: ({ table }) => ( ), }); return ; }; export default Example; ```