Is organizing a table into separate sections helpful?

I'm currently working on a personal project using Material UI, but I have a more general query regarding table implementation. I have designed a layout in Figma that I like, but I am struggling to translate it into code.

https://i.sstatic.net/NoWEB.png

My issue lies with the MUI table I have created - there are two main problems. First, I am unsure how to integrate the top 3 headers seamlessly into the table without them getting misaligned when resizing the screen. Secondly, I am perplexed about how to structure the table into sections and justify the headers accordingly.

It has been a challenging day trying to work through this problem; what seemed like a straightforward design has become quite complex as I try to segment the table into three distinct parts.

https://i.sstatic.net/Tbkmw.png

Here is my current code:

import { styled } from "@mui/material/styles";
import Grid from "@mui/material/Grid";
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 Box from "@mui/material/Box";
import Paper from "@mui/material/Paper";
import Typography from "@mui/material/Typography";

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),
];

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

export default function DenseTable() {
    return (
        <Box sx={{ mt: 3 }}>
            <Grid container>
                <Grid item xs>
                    <Typography sx={{ fontSize: 16 }} component="h2">
                        <b>Header 1</b>
                    </Typography>
                </Grid>
                <Grid item xs>
                    <Typography sx={{ fontSize: 16 }} component="h2">
                        <b>header 2</b>
                    </Typography>
                </Grid>
                <Grid item xs>
                    <Typography sx={{ fontSize: 16 }} component="h2">
                        <b>Header 3</b>
                    </Typography>
                </Grid>
            </Grid>
            {/*  */}
            <TableContainer component={Paper}>
                <Table sx={{ minWidth: 650 }} size="small" aria-label="a dense table">
                    <TableHead>
                        <TableRow>
                            <TableCell>header 1</TableCell>
                            <TableCell>header 2</TableCell>
                            <TableCell>header 3 </TableCell>
                            <TableCell>header 4</TableCell>
                            <TableCell>header 5</TableCell>
                        </TableRow>
                    </TableHead>
                    <TableBody>
                        {rows.map((row) => (
                            <StyledTableRow
                                key={row.name}
                                sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
                            >
                                <TableCell component="th" scope="row">
                                    {row.name}
                                </TableCell>
                                <TableCell align="right">{row.calories}</TableCell>
                                <TableCell align="right">{row.fat}</TableCell>
                                <TableCell align="right">{row.carbs}</TableCell>
                                <TableCell align="right">{row.protein}</TableCell>
                            </StyledTableRow>
                        ))}
                    </TableBody>
                </Table>
            </TableContainer>
        </Box>
    );
}

Answer №1

When dealing with problem One, remember that you can simply add another TableRow within the table instead of creating headers outside of it. Also, utilize the colspan property in the TableCell to specify how many columns each cell should span.

<TableCell colspan={5}>
  ...
</TableCell>

As for problem Two, the issue seems to be related to styling. You can visually separate sections in the table by setting the borderRight for a specific cell to mark it as the boundary of a section.

I've put together a rough example based on your code and figma layout. It may need refinement, but it serves as a starting point for you.

https://i.sstatic.net/HfT0r.png

It was an interesting problem to solve!

Check out the Working CodeSandbox here.

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

How can I put a row at full-width in a Material-UI table in React

I need assistance with displaying data in a table using JSX code: const StudentsTable = (props) => { const classes = useStyles(); return ( <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple ...

Tips on saving this information in a MySQL database

I'm currently developing a php script that collects and saves links in mysql. However, I've encountered an issue where the script sometimes captures multiple links for the same download, as shown below: http://www.fileserve.com/file/XXXXXX http: ...

Tips on using htmlspecialchars in combination with a href:To safely include links in

If I have the following code: $text = "please visit this <a href='http://example.com'>site</a>." $text = htmlspecialchars($text); echo $text; The output will be please visit this <a href='http://example.com'>site< ...

Generating an HTML table from information stored in a text file

As a beginner in web design, I am looking to create an HTML table using data from a text file. I'm unsure of the best approach to take, so any guidance or pointers would be greatly appreciated. ...

jQuery-powered unique serial numbers for tables

I've encountered an issue with my dynamic table that consists of 2 dynamic rows including students, their subjects, and marks. The code in question is provided below: Feel free to check out the code here Snippet for Serial Number function gene ...

What is the best way to include a borderTop in a React Material UI Table component?

https://i.sstatic.net/RIViY.png Is there a way to add a top border to the table above? I attempted const styles = theme => { root : { borderTopWidth: 1, borderColor: 'red'} } ... class TableComponent ... { classes } = this.props; & ...

How can I make multiple elements change color when hovering with CSS?

Hey there! I have a little design challenge that I need help with. On my website (), I am trying to make multiple elements of a specific item change color when the user hovers over the text. If you hover over the "more" menu item, you'll notice that o ...

Is it possible to have the Target='_blank' attribute open the link in a new window instead of a new tab?

Is there a way to achieve this? When using Firefox, the link opens in a new tab, which I prefer to avoid users having to adjust settings in their browsers. I am looking for a solution where a pop-up contact form appears whenever a user clicks on 'co ...

oj-select-one displays a comprehensive list of values in the dropdown

Typically, oj-select-one will only display the first 15 values before requiring the user to search for more. Is there a way to show all values in the dropdown list without needing to use the search function? I attempted to use minimumResultsForSearch as s ...

Dynamically setting the IMG SRC attribute with the base64 result of a FileReader for file input

Looking for a little guidance on something new, I'll keep it brief because I'm sure it's just some small detail I'm overlooking... Starting with an image like this, where currentImage is the initial existing image path; <img src="{ ...

Issue: Failed to load images while attempting to upload to Supabase

I am currently facing an issue in my next.js app while trying to upload images from a form. Every time I attempt to do so, I encounter the following error message: [Error] Unhandled Promise Rejection: TypeError: Load failed. Unfortunately, the file does no ...

"Oops! Vite seems to be facing an issue as RefreshRuntime.injectIntoGlobalHook function is

Our CRA react app has been transitioned from webpack to Vite. Problem: When running the application locally in production mode, I encounter the following error: 1. Uncaught TypeError: RefreshRuntime.injectIntoGlobalHook is not a function at (index):6:16 ...

Ways to remove the highlighting from a selected list item using CSS/Javascript

I have a problem with a list of images and keywords that act as selections for users. When a user clicks on a selection, it highlights the corresponding image using CSS shadow. However, I am trying to figure out how to deactivate this highlight later on, e ...

React Error: The module 'common' could not be located

I've been searching high and low on the web for a solution to this problem, but so far, nothing I've found has done the trick. I'm fairly new to React, but a friend of mine requested my assistance with some CSS work on his React project, so ...

Issue with MUI components - Unable to resolve @mui/material reference

Having trouble getting a basic mui button to function correctly, any suggestions on what might be going wrong? react_1 | ERROR in ./src/components/formSubmit.js 6:0-39 react_1 | Module not found: Error: Can't resolve '@mui/material' ...

What's the best way to stack two input fields vertically and combine them into a single unit?

My goal is to have two inputs placed inside a container, one above the other with no space in between and without separate borders for each input. I am using Bootstrap, but so far my attempts with vertical alignment have been unsuccessful. Here is the code ...

Is there a way to automatically update the input value when I refresh the page following a click event?

Currently, I have multiple p elements that trigger the redo function upon being clicked. When a p element is clicked, the quest[q] template is loaded onto the .form div. These templates are essentially previously submitted forms that sent values to an obj ...

Tips for preserving the Context API state when navigating between pages in Next.js

Currently, I am working on a project that involves using nextJs and TypeScript. To manage global states within my application, I have implemented the context API. However, a recurring issue arises each time I navigate between pages - my state re-evaluates ...

Material-UI rating component outputs a string instead of a numerical value

I'm encountering an issue with the Material UI rating component. Despite providing it with a number as the initial value (this.props.data.feelings_rating), it returns a string whenever I change it within my app. Below is the relevant code: Rating co ...

Deduce the property type by the existence of the value

Here's a situation I'm trying to address in a simple way: if the entity prop is present, I want the onClick callback to receive the entity string, otherwise it should receive nothing. type SnakeOrCamelDomains = "light" | "switch" | "input_boolean ...