Customizing Material-UI Table Background Color, Border, Font Size, and onClick

Material-UI Tables can be uniquely styled if you target the appropriate component: TableCell, TableRow, Table, or TableContainer. In this demo, I will customize the background color, font size, and borders to create the table in the screenshot below.

MUI Table with background color, large font, and cell border
MUI Table with background color, large font, and cell border

We’ll go over the differences in targeting the header cells and the body cells.

Additionally, I will add an onClick handler and include the TypeScript typing for TableCells.

A Code Sandbox link with full React code is in the Resources section.

Material-UI Table Background Color and Text Color

When setting the background color on a table, you need to consider what the most effective (least code) method is for applying color to the desired areas.

Take a look at the screenshot in the intro. We need to apply background uniquely to the first cell of the header, then uniformly to the rest of the header, and uniformly to the first column of the table body.

We accomplish this through the code below:

<Table sx={{ tableLayout: "auto" }}>
  <TableHead onClick={tableHeaderClickHandler}>
    <TableRow
      sx={{
        backgroundColor: "yellow",
        borderBottom: "2px solid black",
        "& th": {
          fontSize: "1.25rem",
          color: "rgba(96, 96, 96)"
        }
      }}
            >
      <TableCell
        sx={{
          ...tableStyling,
          width: 100,
          backgroundColor: "orange"
        }}
              >
        Food
      </TableCell>
//...more JSX

//In the TableBody
<TableCell

  sx={{
    padding: "0px 0px",
    borderRight: "2px solid black",
    backgroundColor: "lightblue",
    fontSize: "1.1rem"
  }}
>
  {row.name}
</TableCell>

In the TableRow component I set background color using the sx prop. Then in the first child TableCell, I set a difference background color. This overrides the parent background color for that cell.

Later in the TableBody, I set the first cell to have a “lightblue” background color. This cell is coded once but rendered for every row.

Next, I set text color in the TableHeader TableRow using a nested selector. TableCell components that render in a Material-UI TableHeader will render as th elements. This is why the nested selector targets th. In contrast to this, cells in the body section will render as td by default.

Material-UI Table Border

The relevant code for the row and column border can be found in the previous section.

I added a bottom border to the MUI TableRow in the header to give the appearance of the header being separated from the body.

I then added a right border to the first cell of the TableBody. This TableCell is coded once but multiple copies get rendered, one for each element of data.

The border on the right of the ‘title’ column gives a nice visual to immediately see the label column. Remember that there are no columns in the MUI table, only TableCells that get rendered in a certain order.

Here’s how to create a ‘sticky’ first column for your table.

Material-UI Table Cell Font Size

The relevant code for font size can be found in the Background Color section.

Font size in a table is useful for differentiating header text and title column text.

A simple way to increase font size in the TableHeader is to use a nested selector with the sx prop. This allows code to be written once instead of written in the sx prop of every header TableCell.

If you want to increase the text size for the title column, take a look at my code. Simply code the font size increase in the first cell in the table body, then loop through the data and render many copies of the cell.

Material-UI Table onClick (with TypeScript)

MUI Table clicks can happen at a variety of component levels. For example, we can have a click handler on a TableCell and a TableRow, and both of them can trigger from the same click.

Furthermore, we have a significant amount of data in the click event that can be used in the handler. Take a look at the values present in the screenshot below. Values like cellIndex and innerHTML are particularly useful.

Values available in the MUI tablecell click event
Values available in the table cell click event

In my example, I added a click handler at both the TableHead level and the TableCell level (children inside the TableBody). The JSX is abbreviated below.

export default function StylishTable() {
  const [snackbarOpen, setSnackbarOpen] = React.useState(false);
  const [infoText, setInfoText] = React.useState("a data");

  const tableCellClickHandler = 
    (e: React.MouseEvent<HTMLElement>) => 
  {
    console.log((e.target as Element).innerHTML);
  };

  const tableHeaderClickHandler = 
    (e: React.MouseEvent<HTMLElement>) => 
  {
    setSnackbarOpen(true);
    if (((e.target as unknown) as Cell).cellIndex) {
      setInfoText("data");
    } else {
      setInfoText("title");
    }
  };

//JSX snippets
<TableHead onClick={tableHeaderClickHandler} />

//These are cells in the TableBody component
<TableCell onClick={tableCellClickHandler} />
<TableCell onClick={tableCellClickHandler} />
<TableCell onClick={tableCellClickHandler} />
<TableCell onClick={tableCellClickHandler} />

The click handler in the TableHeader could have just as easily been placed on the TableRow that contained all the cells in the header.

The result of the header click handler is that an alert is opened inside a snackbar component. If the cell clicked has an index of zero, then the text in the snackbar displays “This is a title cell”. If the index is greater than zero, then the text displays “This is a data cell”.

The TypeScript typing on the header click handler was challenging. Event targets can be difficult to ‘type’ properly, and the cellIndex value mysteriously gets added to the event target in this click event. Because of this, I simply casted the event target to ‘unknown’ and then casted it as having a cellIndex value.

The click handler on the TableCell is simpler. It can be cast as an Element and then element values such as innerHTML are available. Read this helpful post for more detail on the TypeScript error that occurs if you don’t cast the event target value.

Resources

Here’s a tutorial on the basics of the MUI table.

Check out this article for MUI Table row height.

Code Sandbox link

MUI Table Component API

Share this post:

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.