Setting up Material UI and TanStack Table in a React Project
Demonstrate how to install Material UI and React TanStack Table v8 in a React project, including configuring a basic table component.
npm install @mui/material @mui/x-date-pickers @mui/icons-material @emotion/react @emotion/styled
This command installs Material UI and its peer dependencies necessary for styling the components.
npm install @tanstack/react-table
This command installs the latest version of TanStack Table, formerly known as react-table, for creating flexible and extendable tables in your React project.
import React from 'react';
import { useTable } from '@tanstack/react-table';
import { Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from '@mui/material';
const DataTable = ({ columns, data }) => {
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({ columns, data });
return (
<TableContainer component={Paper} {...getTableProps()}>
<Table>
<TableHead>
{headerGroups.map(headerGroup => (
<TableRow {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<TableCell {...column.getHeaderProps()}>
{column.render('Header')}
</TableCell>
))}
</TableRow>
))}
</TableHead>
<TableBody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row);
return (
<TableRow {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<TableCell {...cell.getCellProps()}>
{cell.render('Cell')}
</TableCell>
);
})}
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
);
};
export default DataTable;
This code snippet creates a reusable DataTable component using Material UI for styling and TanStack Table for handling table logic like rendering rows and columns. It demonstrates the basic setup and integration of both libraries in a React component.