Creating a table with multiple rows condensed into a single row (Using Material-UI/CSS)

Here is the array structure I am working with:

const sample = [
  { name: 'apple', detail: [{'a', 'b'}]},
  { name: 'banana', detail: [{'a', 'b'}]},
];

In order to create a table similar to the image in the following link:

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

The table body has all the details inside cells. However, the table's size is too narrow and does not align properly with the table header.

I'm curious if there's a more efficient way to map multiple data into rows and merge them into one table cell.

The names (apple and banana) should be in the first cell with row span.

Answer №1

To achieve this, utilize the rowSpan property on your TableCell. Simply set it to the value of detail.length + 1

Give this code a shot:

import React, { Fragment } from "react";
import { makeStyles } from "@material-ui/core/styles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";

const useStyles = makeStyles(theme => ({
  root: {
    width: "100%",
    marginTop: theme.spacing(3),
    overflowX: "auto"
  },
  table: {
    minWidth: 700
  }
}));

const sample = [
  { name: "apple", detail: ["a", "b", "c", "d"] },
  { name: "banana", detail: ["a", "b"] }
];

export default function SpanningTable() {
  const classes = useStyles();

  return (
    <Paper className={classes.root}>
      <Table className={classes.table}>
        <TableHead>
          <TableRow>
            <TableCell>Fruit</TableCell>
            <TableCell align="right">Buyers</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {sample.map(item => (
            <Fragment>
              <TableRow>
                <TableCell rowSpan={item.detail.length + 1}>
                  {item.name}
                </TableCell>
              </TableRow>
              {item.detail.map(detail => (
                <TableRow>
                  <TableCell>{detail}</TableCell>
                </TableRow>
              ))}
            </Fragment>
          ))}
        </TableBody>
      </Table>
    </Paper>
  );
}

For your convenience, here's a Functional Sample CodeSandbox 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

Positioning the Material UI drawer

Is it possible to incorporate a drawer within a dialog component using material-ui? https://i.sstatic.net/RF1JA.png ...

Client-side rendering for NextJS server components is also supported

I am currently working with Material UI v5.11.16 in a nextjs environment using v13.3.0. I followed the official documentation setup for my nextjs project which can be found here. So far, I have successfully integrated Material UI components without having ...

What is the best way to update the state of a different component?

Snippet: var React = require('react'); var RecipeBox = require('./RecipeBox.jsx'); var AddRecipe = React.createClass({ handleClick: function () { RecipeBox.setState({ adding: false }); }, rend ...

getting images from server with spring boot and reactjs

For my project, I have set up a backend using Spring Boot and a frontend using ReactJS. The images and videos are stored on the server and then retrieved to the front end. Everything works perfectly fine when testing locally on localhost. However, once I ...

Implementing a custom theme for React material-table

I am currently working on integrating react material-table (https://github.com/mbrn/material-table) with my project. My goal is to customize the styling and theme of the table. Here's an example of what I've tried: <MaterialTable options={ ...

The protected routes within a React JS application consistently result in an undefined value

In my ProtectedRoute component for my react application, I am facing an issue with user authentication. I am using react-router-dom v6 to access the token from localStorage, but no matter what, the user variable always returns undefined. import { Outlet, N ...

Attach a tab-icon to a picture

I am looking to add a tab to the bottom border of an image within a gallery. This tab needs to be right up against the image border with no space in between. When clicked, this tab should activate a small JavaScript function that will display the content ...

Utilizing statuses in Typescript React for conditional rendering instead of manually checking each individual variable

It's common for developers, myself included, to perform conditional rendering by checking variable values like this: import React, { useState, useMemo } from 'react' const Page = () => { const [data, setData] = useState<any[]>() ...

Tips for dynamically appending a string to a predefined variable in React

When I was working on creating a text input space using the input type area and utilizing the onChange utility, everything was running smoothly. Now, my task is to incorporate an emoji bar and insert a specific emoji into the input space upon clicking it. ...

Understanding the behavior of CSS float (even after thorough examination of W3C documentation)

I am currently facing an issue related to the float property and have provided a snippet of code below for reference. My goal is to achieve a two-column layout using floats. While I am familiar with other methods to achieve this layout, I am specifically i ...

Explore how to set up Express with React without resorting to using create-react

I am familiar with the react and Node.js Express bundle, but I require assistance. While this question may have been posed by someone else before, I have not come across a similar query within the same framework. The specific question is: How can queries ...

Maintaining consistent row height in bootstrap when displaying or hiding a button

I'm currently working on a project utilizing AngularJS and Bootstrap to create a dynamic form. My goal is to have an 'edit' button display when a user hovers over a specific row of the form. However, I'm facing an issue where the row&ap ...

Switch the style of a set of thumbnail images when clicked

I am working with a set of thumbnails where one has an "p7_current" class applied, giving it a border, while the rest have an "p7_inactive" class removing the border. My goal is to have the last clicked thumbnail in a group of 6 to have the "p7_current" c ...

Concealing the side navigation menu with HTML and CSS

Hey there, I'm trying to make my navbar automatically hide when the mouse is moved. I found an example that I want to use here. Despite reading some online documentation, I just can't seem to figure out how to do it. Here's a snippet of my c ...

Does the JavaScript Map Function Operate Asynchronously?

I've been making changes to the state element properties within a map computePiePercentages(){ var denominator = 1600 if (this.state.total < 1600){ denominator = this.state.total } return this.state.pieChartData.map((item, ...

Get rid of any fonts that are causing rendering delays on amp pages

Encountering issues with Google Lighthouse and AMP Pages https://i.sstatic.net/EXiha.png I have attempted various solutions but none seem to be working <link rel="preload" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400, ...

Development of an Angular 4 application utilizing a bespoke HTML theme

I'm in the process of creating an Angular 4 project using Angular CLI and I need to incorporate a custom HTML theme. The theme includes CSS files, JS files, and font files. Where should I place all of these files? Should they go in the asset folder? O ...

What causes the content area of my <input> element to extend beyond the boundaries of its parent <span> element?

Please Note: I've been working on extracting code from a WordPress environment running the Salient theme. As of now, I haven't been able to simplify the issue to its core form. There is a possibility that I might figure it out myself, but I welco ...

How to design input elements for adding new rows in Material Table

Looking to expand the width of a drop-down list labeled "Birth Place" within the Materialtable component in ReactJS. https://i.sstatic.net/SM77u.png I am aiming for a design similar to the image attached, but I am unsure where to apply the CSS code &apos ...

What is the process for adding a Contact Us page to a website?

I recently created a website using html, css and Javascript. I would like to include a 'get in touch' page where visitors can send me messages directly on the site. What steps should I take to make this happen? Is it necessary to set up a databas ...