Changing the height of tablerows in Material UI v5: A step-by-step guide

I am attempting to adjust the height of the rows in this material-ui code example.

    import * as React from "react";
    import { styled } from "@mui/material/styles";
    import Table from "@mui/material/Table";
    import TableBody from "@mui/material/TableBody";
    import TableCell, { tableCellClasses } 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";

    const StyledTableCell = styled(TableCell)(({ theme }) => ({
      root: {
        height: "20px"
      },
      [`&.${tableCellClasses.head}`]: {
        backgroundColor: theme.palette.common.black,
        color: theme.palette.common.white
      },
      [`&.${tableCellClasses.body}`]: {
        fontSize: 14
      }
    }));

    const StyledTableRow = styled(TableRow)(({ theme }) => ({
      root: {
        height: "20px"
      },
      "&:nth-of-type(odd)": {
        backgroundColor: theme.palette.action.hover
      },
      // hide last border
      "&:last-child td, &:last-child th": {
        border: 0
      }
    }));

    function createData(name, calories, fat, carbs, protein) {
      return { name, calories, fat, carbs, protein };
    }

    const rows = [
      createData("Frozen yoghurt", 159, 6.0, 24, 4.0),
      createData("Ice cream sandwich", 237, 9.0, 37, 4.3),
      createData("Eclair", 262, 16.0, 24, 6.0),
      createData("Cupcake", 305, 3.7, 67, 4.3),
      createData("Gingerbread", 356, 16.0, 49, 3.9)
    ];

    export default function CustomizedTables() {
      return (
        <TableContainer component={Paper}>
          <Table sx={{ minWidth: 700 }} aria-label="customized table">
            <TableHead>
              <TableRow>
                <StyledTableCell>Dessert (100g serving)</StyledTableCell>
                <StyledTableCell align="right">Calories</StyledTableCell>
                <StyledTableCell align="right">Fat&nbsp;(g)</StyledTableCell>
                <StyledTableCell align="right">Carbs&nbsp;(g)</StyledTableCell>
                <StyledTableCell align="right">Protein&nbsp;(g)</StyledTableCell>
              </TableRow>
            </TableHead>
            <TableBody>
              {rows.map((row) => (
                <StyledTableRow key={row.name}>
                  <StyledTableCell component="th" scope="row">
                    {row.name}
                  </StyledTableCell>
                  <StyledTableCell align="right">{row.calories}</StyledTableCell>
                  <StyledTableCell align="right">{row.fat}</StyledTableCell>
                  <StyledTableCell align="right">{row.carbs}</StyledTableCell>
                  <StyledTableCell align="right">{row.protein}</StyledTableCell>
                </StyledTableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      );
    }

I have tried to customize the css like this:

const StyledTableCell = styled(TableCell)(({ theme }) => ({
    root: {
        height: "30px",
        padding: 0,
    },
    [`&.${tableCellClasses.head}`]: {
        backgroundColor: theme.palette.common.black,
        color: theme.palette.common.white,
    },
    [`&.${tableCellClasses.body}`]: {
        fontSize: 14,
    },
}));

const StyledTableRow = styled(TableRow)(({ theme }) => ({
    root: {
        height: "30px",
    },
    "&:nth-of-type(odd)": {
        backgroundColor: theme.palette.action.hover,
    },
    // hide last border
    "&:last-child td, &:last-child th": {
        border: 0,
    },
}));

However, I have not seen any changes take effect. It seems that I may have modified the wrong property. How can I successfully change the row height?

UPDATE

There were buttons in my last column which were preventing the rows from being smaller. The solutions mentioned in the comments and the provided answer have worked.

Answer №1

To utilize the tableRowClasses, you must first import it:

import TableRow, { tableRowClasses } from "@mui/material/TableRow";

Afterwards, adjust your TableRow as needed:

const StyledTableRow = styled(TableRow)(({ theme }) => ({
  [`&.${tableRowClasses.root}`]: {
    height: "200px"
  },

Check out the live Demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a loading image as a placeholder while the Block is loading on the Viewport

Despite my extensive search for a solution to my problem, I have been unable to find one that addresses it directly. I am trying to display a "loading" image for 4 seconds before the content of the div is loaded. Unfortunately, I haven't been able to ...

"Enhance Your Table Design with Zebra Cells Using CSS in rich:data

How can I achieve a zebra color effect in every other cell of a rich:dataTable using CSS? <rich:dataTable value="#{uploader.files}" var="_data" id="files"> <rich:column> <f:facet name="header"> <h:outputText ...

Removing padding from Material UI Container when width is xs can be achieved by adjusting the CSS properties accordingly

When the size of Container changes to xs, I want it to have zero padding. I attempted to achieve this using the following code snippet from https://material-ui.com/api/container/, but so far, I haven't been successful. When I replace maxWidthXs with ...

Add the element to a fresh array only if there are no duplicate values present

I am faced with a challenge involving an array of names where duplicate entries, such as "Kenny," are causing some confusion. I only want each name to be included in the new array once, but I'm struggling to achieve this. Here's my progress so fa ...

Using jQuery to pass multiple data-id attributes via AJAX

Having various tooltip links with distinct "data-id" attributes is a common scenario. <a href="" class id="tooltip" data-id="125">Link</a> <a href="" class id="tooltip" data-id="38">Link 2</a> In such instances, the "125" or "38" f ...

HTML/CSS: Maintain Hover-Over Pop Up Boxes in Position Until Another Element is Hovered Over

Seeking HTML code to maintain a hover-over pop-up box in position on an image map until another section of the image map is hovered over. For example, refer to my code below - when hovering over a country on the map, a pop-up box with information about a ...

How can I send a variable into the DOM using AJAX?

Apologies for posting a question earlier about creating a condition for checkbox without proper investigation. It appears that I need to pass my variables here. function setsession(sessionid, action, data) { $("#totalselection").show(); $. ...

Encountering problems with createMediaElementSource in TypeScript/React when using the Web Audio API

Currently, I am following a Web Audio API tutorial from MDN, but with a twist - I am using TypeScript and React instead of vanilla JavaScript. In my React project created with create-react-app, I am utilizing the useRef hook to reference the audio element ...

Stop the form from submitting when the Enter key is pressed

I am experiencing an issue with my form that contains around 10 input text boxes. When I press the enter key from an input text box, it skips the text boxes in between and goes directly to the submit button. This problem occurs only when using the keyboard ...

Unraveling the mystery: Retrieving event.target.value in a React component

Having trouble accessing the event.target.value from a React child Component, but not an HTML tag? In this scenario: the Button tag (React Component) cannot access event.target.value, while the button tag (HTML tag) can. import React from "react"; impor ...

Tips on creating a keypress function for a div element with the contenteditable attribute

Hey there, I have managed to create a textarea within a div by using -webkit-appearance. However, I am currently struggling to add an event to this div on key press. I have been trying my best to figure it out but seem to be missing something. If you coul ...

What is the method for incorporating PHP's header() function within PayPal JavaScript code?

I'm currently working on integrating Paypal with my website and I've run into some issues handling the various messages sent by Paypal, such as success, failed, and cancelled transactions. Below is a snippet of the Paypal JS code where it manage ...

There was an unexpected token error in the .less file while running npm start, caused by an invalid syntax in the @

This React application was originally built using create-react-app (CRA) with Ant Design (antd). Modifications were made to incorporate server-side rendering (SSR). npm run build executes without any issues. The error arises when running npm start: /User ...

Why is the response from this HTTP request displaying array lengths instead of actual content?

I am currently working on a project involving fetching data asynchronously from an API. Everything seems to be working fine, except for when I attempt to add the correct answer to the incorrect answers array. Instead of displaying the content, only the len ...

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

passing parameters via routes

I've been working on passing parameters through the URL using this code, but it doesn't seem to be functioning properly. I suspect that the issue lies in the "get(\users:id)" part, but I'm unsure of the correct way to do it: $.ajax ...

Transferring information from parent page to child page using Angular version 8.2.4

As a newcomer to Angular, I am facing a challenge in sharing data between pages upon loading the main page. The structure involves using dynamic forms to generate dynamic pages within the main page. However, when trying to pass data from the main page to t ...

The default value of a TextField in React JS using Material UI remains static and does not update

Whenever the state changes, I am trying to update the default value of a TextField but it doesn't seem to work. I have a feeling that it is not re-rendering. <TextField multiline={true} rows={15} disabled id="outlined-basi ...

Discovering ways to showcase JSON response in JavaScript or PHP

Currently, I am integrating the Coin Warz API into my website. The API sends responses in JSON format. I have attempted to display this data in a table format using PHP, but unfortunately, I am encountering difficulties. The JSON Response is as follows: [ ...

Is it possible to input tab characters in a TextField?

I am working with a multi-line MUI TextField and my objective is to input JSON text. However, I encountered an issue where pressing the tab key causes the component to lose focus and shift to the next element on the page. Is there a way to prevent the ta ...