Open In App

React MUI Table Display

React Tables display information in a way that’s easy to scan, so that users can look for patterns and insights. They can be embedded in primary content, such as cards. Material UI is a library of React UI components that implements Google’s Material Design. 

The different types of React tables are:



  1. Simple Table: This is a basic table with fixed column and row numbers.
  2. Data Table: This table is used where we have large amount of data in use case where one needs to finds insights about data.
  3. Dense Table: This is a table where the table size and spacing between the rows is minimized .
  4. Collapsible Table: This is a table with expandable rows, revealing more information. It utilizes the Collapse component.
  5. Spanning Table: This is a table where we can span multiple rows or columns together. A Billing Table might be a good example of spanning table.
  6. Virtualized Table: This is a table where a huge amount of data is handle inside a single frame rather than using pagination or data table.

Different props to be used in React Tables are:

In this article, we will see how to create tables with MUI in React. First we will need to create our sample application for that follow the following steps.



Step 1: Create a React application using the following command :

npx create-react-app myapp

Step 2: After creating the app ,move to its directory using the following command:

cd myapp

Step 3: Now install the material-UI modules using the following command.

npm install @mui/material @emotion/react @emotion/styled
npm install @mui/icons-material

Project Structure: After completing the above steps the project directory will look like:

Project Directory

Example 1: In this example we will build a simple table .We are creating a table for our a automobile list we can use to display the prices and its features.Different components like color, capacity, fuel, price are being used here. 

First we will create a file SimpleTable.js inside the /src directory which will contain our table data items. The required components are imported from the MUI Library like Body,Cell,Head,Row etc. The createData function returns the required data which will be used to display information. Rows are created using this function. The export function exports the Table to used inside different webpages.

SimpleTable.js




import * as React from 'react';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
 
function createData(name, color, capacity, fuel, price) {
    return { name, color, capacity, fuel, price };
}
 
const rows = [
    createData('TATA HARRIER', 'BLACK', 6, 'DIESEL', '14 LACS'),
    createData('MAHINDRA THAR', 'RED', 4, 'DIESEL', '16 LACS'),
    createData('MARUTI SWIFT', 'WHITE', 5, 'PETROL', '9 LACS'),
    createData('MG HECTOR', 'BLACK', 5, 'PETROL', '18 LACS'),
    createData('MERCEDES GLS', 'WHITE', 5, 'DIESEL', '52 LACS'),
];
 
export default function SimpleTable() {
    return (
        <TableContainer component={Paper}>
            <Table sx={{ minWidth: 650 }} aria-label="simple table">
                <TableHead>
                    <TableRow>
                        <TableCell>
                            NAME
                        </TableCell>
                        <TableCell align="right">
                            COLOR
                        </TableCell>
                        <TableCell align="right">
                            CAPACITY
                        </TableCell>
                        <TableCell align="right">
                            FUEL
                        </TableCell>
                        <TableCell align="right">
                            PRICE (Rs)
                        </TableCell>
                    </TableRow>
                </TableHead>
                <TableBody>
                    {rows.map((row) => (
                        <TableRow
                            key={row.name}
                            sx={{ '&:last-child td, &:last-child th':
                                { border: 0 } }}
                        >
                            <TableCell component="th" scope="row">
                                {row.name}
                            </TableCell>
                            <TableCell align="right">
                                {row.color}
                            </TableCell>
                            <TableCell align="right">
                                {row.capacity}
                            </TableCell>
                            <TableCell align="right">
                                {row.fuel}
                            </TableCell>
                            <TableCell align="right">
                                {row.price}
                            </TableCell>
                        </TableRow>
                    ))}
                </TableBody>
            </Table>
        </TableContainer>
    );
}

After creating the creating our SimpleTable, we will import it in our base file App.js. Update the App.js file in /src directory with the below code.

App.js




import React from "react";
import SimpleTable from "./SimpleTable";
 
function App() {
return (
    <div>
    <SimpleTable />
    </div>
);
}
export default App;

Step to run the application: Now ,Run the Application: Use the following command to run the Application.

npm start

Output: Go To  http://localhost:3000/ and following result will be displayed:

A Simple Table

Example 2: In this example we are creating a table with collapsible rows which can be used to display additional information specific to that data row. It creates a clickable button which expand or collapse the details of a data item. In our Car Catalogue example we can provide additional information like past purchases with customer id and their dates with quantity.

First we create a new file called CollapsibleTable.js inside our /src directory.In this we will import all our required MUI Library like Box,Collapse,IconButton etc. The createData function created the data items required with a history component which will display the past previous of the items by the user. Row function creates individual row items with collapsible data which is imported inside the table.

CollapsibleTable.js




import * as React from 'react';
import PropTypes from 'prop-types';
import Box from '@mui/material/Box';
import Collapse from '@mui/material/Collapse';
import IconButton from '@mui/material/IconButton';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Typography from '@mui/material/Typography';
import Paper from '@mui/material/Paper';
import KeyboardArrowDownIcon from
    '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from
    '@mui/icons-material/KeyboardArrowUp';
 
function createData(name, color, fuel, capacity, price) {
    return {
        name,
        color,
        fuel,
        capacity,
        price,
        history: [
            {
                date: '2020-01-05',
                customerId: '11091700',
                amount: 3,
            },
            {
                date: '2020-01-02',
                customerId: 'Anonymous',
                amount: 1,
            },
        ],
    };
}
 
function Row(props) {
    const { row } = props;
    const [open, setOpen] = React.useState(false);
 
    return (
        <React.Fragment>
            <TableRow sx={{ '& > *': { borderBottom: 'unset' } }}>
                <TableCell>
                    <IconButton
                        aria-label="expand row"
                        size="small"
                        onClick={() => setOpen(!open)}
                    >
                        {open ? <KeyboardArrowUpIcon /> :
                        <KeyboardArrowDownIcon />}
                    </IconButton>
                </TableCell>
                <TableCell component="th" scope="row">
                    {row.name}
                </TableCell>
                <TableCell align="right">{row.color}</TableCell>
                <TableCell align="right">{row.fuel}</TableCell>
                <TableCell align="right">{row.capacity}</TableCell>
                <TableCell align="right">{row.price}</TableCell>
            </TableRow>
            <TableRow>
                <TableCell style={{ paddingBottom: 0,
                    paddingTop: 0 }} colSpan={6}>
                    <Collapse in={open} timeout="auto" unmountOnExit>
                        <Box sx={{ margin: 1 }}>
                            <Typography variant="h6"
                                gutterBottom component="div">
                                History
                            </Typography>
                            <Table size="small"
                                aria-label="purchases">
                                <TableHead>
                                    <TableRow>
                                        <TableCell>
                                            Date
                                        </TableCell>
                                        <TableCell>
                                            Customer
                                        </TableCell>
                                        <TableCell align="right">
                                            Amount
                                        </TableCell>
                                        <TableCell align="right">
                                            Total price ($)
                                        </TableCell>
                                    </TableRow>
                                </TableHead>
                                <TableBody>
                                    {row.history.map
                                        ((historyRow) => (
                                        <TableRow key=
                                            {historyRow.date}>
                                            <TableCell
                                                component="th"
                                                scope="row">
                                                {historyRow.date}
                                            </TableCell>
                                            <TableCell>
                                                {historyRow.customerId}
                                            </TableCell>
                                            <TableCell align="right">
                                                {historyRow.amount}
                                            </TableCell>
                                            <TableCell align="right">
                                                {Math.round
                                                (historyRow.amount
                                                * row.price * 100) / 100}
                                            </TableCell>
                                        </TableRow>
                                    ))}
                                </TableBody>
                            </Table>
                        </Box>
                    </Collapse>
                </TableCell>
            </TableRow>
        </React.Fragment>
    );
}
 
Row.propTypes = {
    row: PropTypes.shape({
        color: PropTypes.string.isRequired,
        capacity: PropTypes.number.isRequired,
        fuel: PropTypes.string.isRequired,
        history: PropTypes.arrayOf(
            PropTypes.shape({
                amount: PropTypes.number.isRequired,
                customerId: PropTypes.string.isRequired,
                date: PropTypes.string.isRequired,
            }),
        ).isRequired,
        name: PropTypes.string.isRequired,
        price: PropTypes.number.isRequired,
    }).isRequired,
};
 
const rows = [
    createData('TATA HARRIER', 'BLACK', 'DIESEL', 6, 1400000),
    createData('MAHINDRA THAR', 'RED', 'DIESEL', 4, 1600000),
    createData('MARUTI SWIFT', 'WHITE', 'PETROL', 5, 900000),
    createData('MG HECTOR', 'BLACK', 'PETROL', 5, 1800000),
    createData('MERCEDES GLS', 'WHITE', 'DIESEL', 5, 5200000),
];
 
export default function CollapsibleTable() {
    return (
        <TableContainer component={Paper}>
            <Table aria-label="collapsible table">
                <TableHead>
                    <TableRow>
                        <TableCell />
                        <TableCell>
                            NAME
                        </TableCell>
                        <TableCell align="right">
                            COLOR
                        </TableCell>
                        <TableCell align="right">
                            FUEL
                        </TableCell>
                        <TableCell align="right">
                            CAPACITY
                        </TableCell>
                        <TableCell align="right">
                            PRICE (RS)
                        </TableCell>
                    </TableRow>
                </TableHead>
                <TableBody>
                    {rows.map((row) => (
                        <Row key={row.name} row={row} />
                    ))}
                </TableBody>
            </Table>
        </TableContainer>
    );
}

After creating the creating our CollpasibleTable, we will import it in our base file App.js. Update the App.js file to import CollapsibleTable.

App.js:




import React from "react";
import CollapsibleTable from "./CollapsibleTable";
 
function App() {
    return (
        <div>
            <CollapsibleTable />
        </div>
    );
}
export default App;

Step to run the application: Now ,Run the Application: Use the following command to run the Application.

npm start

Output: Go To  http://localhost:3000/ and following result will be displayed:

Collapsible Table

Reference: https://mui.com/material-ui/react-table/


Article Tags :