Async Loading Feature Guide
While you are fetching your data, you may want to show some loading indicators. Material React Table has some nice loading UI features built in that look better than a simple spinner.
This guide is mostly focused on the loading UI features. Make sure to also check out the Remote Data and React Query examples for server-side logic examples.
Relevant Props
# | Prop Name | Type | Default Value | More Info Links | |
---|---|---|---|---|---|
1 |
| Material UI LinearProgress Props | |||
2 |
| Material UI Skeleton Props | |||
Relevant State Options
isLoading UI
Rather than coding your own spinner or loading indicator, you can simply set the isLoading
state to true
, and Material React Table will show progress bars and cell skeletons for you.
<MaterialReactTablecolumns={columns}data={data ?? []} //fallback to array if data is undefinedstate={{ isLoading: true }}/>
First Name | Last Name | Email | City |
---|---|---|---|
1import React, { useMemo } from 'react';2import MaterialReactTable, { MRT_ColumnDef } from 'material-react-table';3import { Person } from './makeData';45const Example = () => {6 const columns = useMemo<MRT_ColumnDef<Person>[]>(7 //column definitions...28 );2930 return (31 <MaterialReactTable32 columns={columns}33 data={[]}34 state={{ isLoading: true }}35 />36 );37};3839export default Example;40
Only Show Progress Bars or Skeletons
If you do not want both progress bars and cell skeletons to show, you can use the showProgressBars
and showSkeletons
states, instead.
<MaterialReactTablecolumns={columns}data={data ?? []} //fallback to array if data is undefinedstate={{ showProgressBars: true }} //or showSkeletons/>
Customize Linear Progress Bars
You can customize the linear progress bars by passing props to the muiLinearProgressProps
prop.
First Name | Last Name | Email | City |
---|---|---|---|
Dylan | Murray | dmurray@yopmail.com | East Daphne |
Raquel | Kohler | rkholer33@yopmail.com | Columbus |
Ervin | Reinger | ereinger@mailinator.com | South Linda |
Brittany | McCullough | bmccullough44@mailinator.com | Lincoln |
Branson | Frami | bframi@yopmain.com | New York |
Kevin | Klein | kklien@mailinator.com | Nebraska |
1import React, { useEffect, useMemo, useState } from 'react';2import MaterialReactTable, { MRT_ColumnDef } from 'material-react-table';3import { data, Person } from './makeData';4import { Button } from '@mui/material';56const Example = () => {7 const columns = useMemo<MRT_ColumnDef<Person>[]>(8 //column definitions...29 );3031 const [progress, setProgress] = useState(0);3233 //simulate random progress for demo purposes34 useEffect(() => {35 const interval = setInterval(() => {36 setProgress((oldProgress) => {37 const newProgress = Math.random() * 20;38 return Math.min(oldProgress + newProgress, 100);39 });40 }, 1000);41 return () => clearInterval(interval);42 }, []);4344 return (45 <MaterialReactTable46 columns={columns}47 data={data}48 muiLinearProgressProps={({ isTopToolbar }) => ({49 color: 'secondary',50 variant: 'determinate', //if you want to show exact progress value51 value: progress, //value between 0 and 10052 sx: {53 display: isTopToolbar ? 'block' : 'none', //hide bottom progress bar54 },55 })}56 renderTopToolbarCustomActions={() => (57 <Button onClick={() => setProgress(0)} variant="contained">58 Reset59 </Button>60 )}61 state={{ showProgressBars: true }}62 />63 );64};6566export default Example;67
Full Loading and Server-Side Logic Example
Here is a copy of the full React Query example.
First Name | Last Name | Address | State | Phone Number |
---|---|---|---|---|
1import React, { useMemo, useState } from 'react';2import MaterialReactTable, {3 MRT_ColumnDef,4 MRT_ColumnFiltersState,5 MRT_PaginationState,6 MRT_SortingState,7} from 'material-react-table';8import { IconButton, Tooltip } from '@mui/material';9import RefreshIcon from '@mui/icons-material/Refresh';10import {11 QueryClient,12 QueryClientProvider,13 useQuery,14} from '@tanstack/react-query';1516type UserApiResponse = {17 data: Array<User>;18 meta: {19 totalRowCount: number;20 };21};2223type User = {24 firstName: string;25 lastName: string;26 address: string;27 state: string;28 phoneNumber: string;29};3031const Example = () => {32 const [columnFilters, setColumnFilters] = useState<MRT_ColumnFiltersState>(33 [],34 );35 const [globalFilter, setGlobalFilter] = useState('');36 const [sorting, setSorting] = useState<MRT_SortingState>([]);37 const [pagination, setPagination] = useState<MRT_PaginationState>({38 pageIndex: 0,39 pageSize: 10,40 });4142 const { data, isError, isFetching, isLoading, refetch } =43 useQuery<UserApiResponse>({44 queryKey: [45 'table-data',46 columnFilters, //refetch when columnFilters changes47 globalFilter, //refetch when globalFilter changes48 pagination.pageIndex, //refetch when pagination.pageIndex changes49 pagination.pageSize, //refetch when pagination.pageSize changes50 sorting, //refetch when sorting changes51 ],52 queryFn: async () => {53 const fetchURL = new URL(54 '/api/data',55 process.env.NODE_ENV === 'production'56 ? 'https://www.material-react-table.com'57 : 'http://localhost:3000',58 );59 fetchURL.searchParams.set(60 'start',61 `${pagination.pageIndex * pagination.pageSize}`,62 );63 fetchURL.searchParams.set('size', `${pagination.pageSize}`);64 fetchURL.searchParams.set(65 'filters',66 JSON.stringify(columnFilters ?? []),67 );68 fetchURL.searchParams.set('globalFilter', globalFilter ?? '');69 fetchURL.searchParams.set('sorting', JSON.stringify(sorting ?? []));7071 const response = await fetch(fetchURL.href);72 const json = (await response.json()) as UserApiResponse;73 return json;74 },75 keepPreviousData: true,76 });7778 const columns = useMemo<MRT_ColumnDef<User>[]>(79 () => [80 {81 accessorKey: 'firstName',82 header: 'First Name',83 },84 {85 accessorKey: 'lastName',86 header: 'Last Name',87 },88 {89 accessorKey: 'address',90 header: 'Address',91 },92 {93 accessorKey: 'state',94 header: 'State',95 },96 {97 accessorKey: 'phoneNumber',98 header: 'Phone Number',99 },100 ],101 [],102 );103104 return (105 <MaterialReactTable106 columns={columns}107 data={data?.data ?? []} //data is undefined on first render108 initialState={{ showColumnFilters: true }}109 manualFiltering110 manualPagination111 manualSorting112 muiToolbarAlertBannerProps={113 isError114 ? {115 color: 'error',116 children: 'Error loading data',117 }118 : undefined119 }120 onColumnFiltersChange={setColumnFilters}121 onGlobalFilterChange={setGlobalFilter}122 onPaginationChange={setPagination}123 onSortingChange={setSorting}124 renderTopToolbarCustomActions={() => (125 <Tooltip arrow title="Refresh Data">126 <IconButton onClick={() => refetch()}>127 <RefreshIcon />128 </IconButton>129 </Tooltip>130 )}131 rowCount={data?.meta?.totalRowCount ?? 0}132 state={{133 columnFilters,134 globalFilter,135 isLoading,136 pagination,137 showAlertBanner: isError,138 showProgressBars: isFetching,139 sorting,140 }}141 />142 );143};144145const queryClient = new QueryClient();146147const ExampleWithReactQueryProvider = () => (148 <QueryClientProvider client={queryClient}>149 <Example />150 </QueryClientProvider>151);152153export default ExampleWithReactQueryProvider;154