The use of Material-UI collapse animation in a table results in the insertion of div elements, triggering a validateDOMNesting warning

Having a data-filled table, I am looking to implement smooth transitions when adding or deleting an item. This is a ReactJS project utilizing Material-UI.

The desired effect is similar to the one demonstrated in their example. While they use a List component, my implementation involves a table. Here's a snippet of the code:

<TableBody>
    <TransitionGroup component={null} id="ffff">
        {(data?.maintenanceRequests || []).map((form) => (
            <Collapse key={form.id} component={TableRow}>

                <TableCell>{form.building}</TableCell>
                <TableCell>{form.dueDate ? form.dueDate : '-'}</TableCell>
                <TableCell align="right">
                    <IconButton component={Link} to={`request/${form.id}`}>
                        <EditIcon />
                    </IconButton>
                    <IconButton onClick={() => deleteReq({ variables: { deleteMaintenanceRequestId: form.id }, refetchQueries: [{ query: GET_MAINTENANCE_REQUESTS }] })}>
                        <DeleteIcon />
                    </IconButton>
                </TableCell>

            </Collapse>
        ))}
    </TransitionGroup>
</TableBody>

Using this code triggers warnings such as:

Warning: validateDOMNesting(...): <td> cannot appear as a child of <div>.
And
Warning: validateDOMNesting(...): <div> cannot appear as a child of <tr>.

I have already specified the components that and should wrap. Upon inspecting the element, I noticed that the TransitionGroup component adds two nested div elements, hence the warnings. The challenge now lies in resolving these issues.

Answer №1

If you are looking for an alternative to using the mui table in this scenario, here is a potential solution:

import {
  Collapse,
  IconButton,
  TableCell,
  TableRow,
  Table,
  TableContainer,
  Paper,
  Button
} from '@mui/material'
import { useState } from 'react'
import { TransitionGroup, CSSTransition } from 'react-transition-group'

import DeleteIcon from '@mui/icons-material/Delete'

const data = [
  { id: 1, building: 'A', dueDate: '12/12/12' },
  { id: 2, building: 'b', dueDate: '12/12/12' },
  { id: 3, building: 'c', dueDate: '12/12/12' },
  { id: 4, building: 'd', dueDate: '12/12/12' },
  { id: 5, building: 'e', dueDate: '12/12/12' },
  { id: 6, building: 'f', dueDate: '12/12/12' },
  { id: 7, building: 'g', dueDate: '12/12/12' },
  { id: 8, building: 'h', dueDate: '12/12/12' }
]

const alpha = 'ABCDEFGHIGKLMNOPQRSTUVWXYZ'

const CustomTable = () => {
  // const textFieldClasses: any = textfieldUseStyles()c
  const [ListData, setListData] = useState(data)

  const handleAddData = () => {
    const newData = [
      ...ListData,
      {
        id: ListData.length + 1,
        building: alpha.charAt(Math.floor(Math.random() * alpha.length)),
        dueDate: '12/12/12'
      }
    ]
    setListData(newData)
  }

  const handleRemoveData = (id) => {
    const newData = ListData.filter(item => item.id !== id)
    setListData(newData)
  }

  return (
    <TransitionGroup>
      <TableContainer component={Paper}>
        <Table sx={{ minWidth: 650 }} aria-label="simple table">
          <TransitionGroup>
            {ListData.map(form => (
              <Collapse key={form.id}>
                <TableRow className="item">
                  <TableCell>{form.building}</TableCell>
                  <TableCell>{form.dueDate ? form.dueDate : '-'}</TableCell>
                  <TableCell align="right">
                    <IconButton onClick={() => handleRemoveData(form.id)}>
                      <DeleteIcon />
                    </IconButton>
                  </TableCell>
                </TableRow>
              </Collapse>
            ))}
          </TransitionGroup>
        </Table>
        <Button sx={{ mt: 2, width: '100%' }} onClick={handleAddData}>
          Add Item
        </Button>
      </TableContainer>
    </TransitionGroup>
  )
}

export default CustomTable

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

Is there a way to change the default style for a specific tab in CSS?

I'm struggling to customize the style of the currently active tab, but I'm encountering issues with some of the changes not taking effect. This is what I have tried: const StyledTab = withStyles({ root: { color: '#0071bc', ...

What is the best way to send props from a child component to its parent in a React

I'm a beginner in React and I'm attempting to develop a "CV-Generator" similar to the one shown here. In this application, whenever a user inputs data in any of the input fields, it is automatically displayed in the render preview on the right si ...

Transferring data between different elements in a React application

I am currently learning React and facing some challenges in terms of passing data between components. Even after reviewing various tutorials and blogs, I am still struggling to make things work. Within my project, I have two child components named Body-c ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

Having trouble with UseSelector in React Redux?

I am currently working on a exercise to better understand the react-redux process, but I seem to have hit a roadblock. Any assistance would be greatly appreciated. One interesting observation is that when I subscribe and log the store into the console, it ...

When an absolute positioned DIV is nested inside a relatively positioned DIV, it disappears when the page is scrolled

A unique feature of my DIV is that it remains fixed at the top of the page as you scroll. This is achieved by setting its position to fixed. However, within this main container, I have another div with a relative position. While the content in the relative ...

Dynamic Bootstrap User Authentication Form

Currently, I am in the process of constructing a login form for my web application and have opted to use Bootstrap for its styling. To ensure that the screen is responsive, I've integrated the following "Meta Tag" into the structure: <meta name="v ...

I'm having trouble adding headers to my axios post request. The post route functions correctly in Postman but does not work when using axios. Can anyone

Implementing JWT for protecting a post route in my nodejs, express, react application has been quite a challenge. While testing with postman and adding the JWT token to the headers works flawlessly to add users to the database, I encounter a 401 response ( ...

Echo result triggers a color change in the table cell

Working on a piece of code that should change the background color of the first td element based on ping results. If success, it becomes green; if failed, it turns red. The issue I'm facing is that while I can display images or use different methods ...

Using Express JS to Serve React JS Site With Path Exceeding a Simple Subdirectory

Currently, my website is powered by React JS with an Express JS Backend handling the server. The backend includes an API for fetching data from a database and ultimately sends out the constructed website. Take a look at my index.js file within the backend: ...

Customize tooltip and speed dial styles in React using Material UI

I'm having trouble customizing the tooltip appearance and adjusting the position of the speed dial. While attempting to do both, I encountered an error. const useStyles = makeStyles((theme) => ({ root: { height: 380, transform: "tran ...

The image is non-adjustable to different screen sizes

Currently, I am in the process of revamping a friend's website using Next.js and Tailwind. However, I've encountered a challenge with the background image specifically on iPhones. While it appears fine on browsers like Chrome and Safari as well a ...

Creating a button within a card: tips and tricks

As I work on designing web sites, I often face challenges. One of my go-to tools is bootstrap, especially when creating card elements. Here is the code I typically use for creating cards: <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/c ...

What is the best way to pinpoint a specific Highcharts path element?

I am currently working on drawing paths over a graph, and I am looking to dynamically change their color upon hovering over another element on the page - specifically, a list of data points displayed in a div located on the right side of my webpage. Below ...

I am interested in updating the color of the active item on the navbar

I am looking to modify the color of the active page, Here is the HTML code snippet: <html> <head> <title>John Doe - Portfolio</title> <link rel="stylesheet" href="custom-style.css"> <link rel=" ...

What is preventing me from viewing my cards in flex or grid layout?

Recently, I created cards for my team members, but encountered layout issues despite using CSS Flexbox and CSS3 Grid. Although both are supported by my browser, the problem persists. However, the layout works perfectly on mobile devices! I experimented wi ...

Looking to have the image float after reducing the size of the windows in html?

For my webpage, I want an image to appear on the extreme left when the browser is maximized, but then move to the extreme right when the browser is minimized. I've tried using float, but it doesn't seem to be working. Any suggestions on how to ac ...

What is the best way to ensure the menu background aligns perfectly with the header in HTML/CSS?

Issue: Menu background doesn't align with header. (visible in the image provided below) VIEW IMAGE Any suggestions on how to resolve this alignment problem? CSS CODE : .header { margin:0px auto; max-width: 960px; } #header { height:30 ...

Material UI - Array of Chips

I have been working on creating a ReactJS component that displays an array of chips with unique styling for each one. To achieve this, I created individual makeStyles classes for the chips. However, I encountered difficulties in dynamically changing the cl ...

A web page with a full-width header, content constrained to a set width, logo elements displayed with flexbox, and a footer that

I've been facing challenges in making this website responsive on both desktop and mobile devices. Initially, the header background image wasn't displaying as intended, followed by issues with the flexbox logo elements in the header and the sticky ...