Expanded MUI collapsible table squeezed into a single cell

I'm experimenting with using the MUI table along with Collapse to expand and collapse rows. However, I've noticed that when utilizing collapse, the expanded rows get squished into one cell. How can I adjust the alignment of the cells within the parent table?

 export default function App() {
  const [expanded, setExpanded] = useState(false);

  return (
    <Table>
      <TableHead>
        <TableRow>
          <TableCell />
          <TableCell>Header 1</TableCell>
          <TableCell>Header 2</TableCell>
          <TableCell>Header 3</TableCell>
          <TableCell>Header 4</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        <TableRow>
          <TableCell onClick={() => setExpanded(!expanded)}>Expand</TableCell>
          <TableCell>A</TableCell>
          <TableCell>B</TableCell>
          <TableCell>C</TableCell>
          <TableCell>D</TableCell>
        </TableRow>
        <Collapse in={expanded} timeout="auto" unmountOnExit>
          <TableRow>
            <TableCell />
            <TableCell>E</TableCell>
            <TableCell>F</TableCell>
            <TableCell>G</TableCell>
            <TableCell>H</TableCell>
          </TableRow>
        </Collapse>
      </TableBody>
    </Table>
  );
};

By removing the Collapse feature, the table displays in the correct format. e.g. current state is:

The desired result post-expansion would look like this:

Answer №1

My method for achieving this is as follows:

<Table>
    <TableHead>
        <TableRow>
          <TableCell padding="checkbox"/>
          <TableCell>Area name</TableCell>
          <TableCell>2011</TableCell>
          <TableCell>2012</TableCell>
          <TableCell>2013</TableCell>
          <TableCell>2014</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        <TableRow>
          <TableCell padding="checkbox">
            <IconButton
              size="small"
              onClick={() => setOpen(prev => !prev)}
            >
              {open ? <KeyboardArrowUpIcon/> : <KeyboardArrowDownIcon/>}
            </IconButton>
          </TableCell>
          <TableCell component="th">Paris</TableCell>
          <TableCell>1000</TableCell>
          <TableCell>2000</TableCell>
          <TableCell>3000</TableCell>
          <TableCell>4000</TableCell>
        </TableRow>
        <TableRow sx={{ visibility: open ? 'visible' : 'collapse' }}>
          <TableCell padding="checkbox"/>
          <TableCell component="th">1st arrondissement</TableCell>
          <TableCell>100</TableCell>
          <TableCell>200</TableCell>
          <TableCell>300</TableCell>
          <TableCell>400</TableCell>
        </TableRow>
      </TableBody>
    </Table>

The key to making a TableRow collapsible is using

sx={{ visibility: open ? 'visible' : 'collapse' }}
.

Answer №2

The main issue here is that the <Collapse /> component is being used as a div, which cannot be wrapped around table rows. To resolve this, you should create a separate table within the Collapse element and ensure that the cells are aligned to maintain uniform size.

For a demonstration, check out this Codesandbox example.

Answer №3

I made some adjustments to the previous solution so that each row can now expand or collapse upon clicking.

import {
  Collapse,
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableRow,
} from '@mui/material'
import { useState } from 'react'

export default function App() {
  const Row = () => {
    const [expanded, setExpanded] = useState(false)

    return (
      <>
        <Table>
          <TableBody>
            <TableRow>
              <TableCell onClick={() => setExpanded(!expanded)}>Expand</TableCell>
              <TableCell colSpan={4}></TableCell>
            </TableRow>
          </TableBody>
        </Table>
        <Collapse in={expanded} timeout='auto' unmountOnExit>
          <Table>
            <TableBody>
              <TableRow>
                <TableCell></TableCell>
                <TableCell>E</TableCell>
                <TableCell>F</TableCell>
                <TableCell>G</TableCell>
                <TableCell>H</TableCell>
              </TableRow>
            </TableBody>
          </Table>
        </Collapse>
      </>
    )
  }

  return (
    <>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell></TableCell>
            <TableCell>Header 1</TableCell>
            <TableCell>Header 2</TableCell>
            <TableCell>Header 3</TableCell>
            <TableCell>Header 4</TableCell>
          </TableRow>
        </TableHead>
      </Table>
      {Array(5)
        .fill()
        .map(item => (
          <Row />
        ))}
    </>
  )
}

Check out the Codesandbox demo 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

Node.js command prompt claims that 'react is non-existent'

Hello everyone! I'm excited to ask my first question on this site. I am relatively new to coding and currently learning React. Yesterday, I started working on my first project. Today, when I tried to initialize live-server and babel compiler for my J ...

Create a custom VueJS component by utilizing an npm package

Looking to navigate around X-frame restrictions? You can check out this npm package: https://www.npmjs.com/package/x-frame-bypass To make it work, include the following tag within your HTML: <iframe is="x-frame-bypass" src="https://example.org/">& ...

How should an iterable be sorted in React?

Let's break down the scenario using pseudo code: {this.props.myIterable.map((iterable) => { return ( <div>iterable.somevalue</div> ) }).sort((a,b) => {return b - a}) To clarify, I am iterating over certain props and displaying ...

Utilizing image backgrounds for hyperlinks in the Android browser

Encountering a minor issue with some <a> tags that have images as background, and the text inside the tags is indented using CSS. However, on the Android browser, part of the string used in HTML appears to cover the background image within the area o ...

Utilizing InputProps in the TextField component for efficient <input /> element usage

Can InputProps be utilized in the <input /> element rather than <TextField /> from Material UI? This is my Input.js component where I am implementing InputProps: const Input = ({name, handleChange, type, handleShowPassword}) => { retur ...

Issues with ontimeupdate event not triggering in Chrome for HTML5 audio files

After creating an HTML5 audio element and setting a listener for when its time updates, I have run into an issue where the ontimeupdate function does not fire in Chrome, including Chrome on Android. The audio plays without any issues in other browsers. va ...

Employing a pair of interdependent v-select components to prevent any duplicate entries

I am currently working with two v-select boxes that share similar data. In my scenario, I extract attachments from an email and load them into an array. The issue I encountered is that the first select box should only allow the selection of one document, w ...

Issue: The directory does not consist of the designated export titled 'Navbar1'

There seems to be an error popping up repeatedly that I believe should not exist. The specific error message reads: ./src/App.js 21:24-31 './components/Navbar/Navbar' does not contain an export named 'Navbar1'. However, here is the co ...

Learn how to implement a feature in your chat application that allows users to reply to specific messages, similar to Skype or WhatsApp, using

I am currently working on creating a chatbox for both mobile and desktop websites. However, I have encountered an obstacle in implementing a specific message reply feature similar to Skype and WhatsApp. In this feature, the user can click on the reply butt ...

The callbackFinished function is not defined in the winwheel library

Every time I attempt to call a function with the callbackFinished property inside the animation of winwheel, I encounter an error stating that the function is not defined, even though it is defined in the same class. import React from 'react' imp ...

Is there a way to insert a location icon into the react bootsrap FormControl text field component?

LocationSearchComponent.js I'm having an issue with empty icon showing as  const LocationSearchComponent = () => { return ( <Form className="locationForm"> <Form.Group> <Form.Contro ...

Experience the captivating AUTOPLAY feature of the mesmerizing FULLSCREEN SLIT SL

I am currently utilizing a slider that is functioning well, however I am encountering an issue with autoplay. Whenever I click on the navigation arrow or Nav dot at the bottom of the slider, the autoplay feature stops working. For more information, please ...

What is the best way to effectively implement component reuse in Flux architecture?

Currently delving into the complexities of Flux and grappling with some logic regarding the store. Imagine I have a component, a single button that controls a vote, like a switch toggling between "Yes" and "No". So, I have my voteButton handling a voteAct ...

Firefox causing images to have a white border after rendering

My image (.png) has a white border only in Firefox, despite the CSS border property being set to 0. Is there a solution to remove this unwanted border around the image? ...

What is the best way to create a reusable component for a Material-UI Snackbar?

Having trouble getting my Alert component to display a message that says "Successfully submitted" in the parent component. The message doesn't seem to be showing up. AlertComponent import React, { useState } from "react"; import { Snackbar, Alert } f ...

Do you have any queries regarding JavaScript logical operators?

I'm struggling with understanding how the && and || operators work in my code. I created a small program to help myself, but it's just not clicking for me. The idea is that when you click a button, the startGame() function would be triggered. va ...

Is it possible to utilize a redux store as the source for translation resources in next-i18next?

My website features contentEditable text, allowing users to edit the text. I am now looking to implement translations so that any user edits are reflected in the translations.json file. I have set up a redux store with actions mirroring the structure of th ...

Enhancing features with jQuery's .animate() function

Can anyone help me figure out why the div on the right is not pushing itself away from the one on the left when I hover over it? I want it to move on mouseenter and return to its original position on mouseleave. The changing background colors are just ther ...

The hyperlink tag doesn't respond to clicks in Safari, yet functions properly in all other web browsers

I'm encountering an issue with my header drop-down menu in Safari—it works perfectly in Chrome, but when I try to open the drop-down menu in Safari, it's unresponsive. Clicking on it does nothing, preventing me from accessing other drop-downs. ...

The parameter of type '{ userInfo: string | null; }' cannot be assigned to type 'never' in this argument

Currently, I am working on creating a context API in React using TypeScript to store user details and tokens. Since I am relatively new to TypeScript, I am facing some challenges understanding the errors below. Can someone please assist me with this? ..... ...