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

Encountering an issue: The type '{ children: Element; }' does not share any properties with type 'IntrinsicAttributes & CookieConsentProviderProps'

I recently updated my packages and now I'm encountering this error. Is there a way to resolve it without reverting back to the previous versions of the packages? I've come across similar errors reported by others, but none of the suggested solut ...

margin-top: automatic adjustment, with a minimum of 50 pixels

I am trying to add a minimum of 50px margin to the top of my footer tag using CSS, but I haven't been successful with the min() function. I'm not sure if I am overlooking something or if there is another correct approach to achieve this. * { ...

Utilize ng-bootstrap in an Angular CLI project by integrating it with npm commands

I've been attempting to set up a project using Angular CLI with ng-bootstrap, but I'm having trouble getting the style to work properly. Here are the exact steps I followed (as outlined in the get-started page): Create a new project using `ng n ...

When the children within a CSS container are floated, set the height of the container to

I've established a simple layout <div class="container"> <div class="sidebar"> </div> <div class="content"> </div> <div style="clear:both;"></div> </div> where .sidebar and .content ...

What is the best approach for addressing null values within my sorting function?

I created a React table with sortable headers for ascending and descending values. It works by converting string values to numbers for sorting. However, my numeric(x) function encounters an issue when it comes across a null value in my dataset. This is th ...

mui table pagination behaving unexpectedly

const initialState = { isDataGridLoading: false, data: [], pageNo: 1, pageSize: 100 } useEffect(() => { const fetchData = () => { updateState('isDataGridLoading', true); console.log('current page nu ...

What is the best location to place Sentry's setUser function in a Next.js application?

I have been working on integrating user data into Sentry's scope globally so that user information is passed to it every time an error or event occurs. My application is developed in Next.js, and I followed the configuration mentioned in Sentry' ...

Java - openpdf - Splitting words using hyphens

We are currently utilizing openpdf 1.3.26 template 2.1 to create PDFs from HTML and CSS. Within our coding, there is a div element styled as follows: .text-block{ display:block; text-align:justify; word-wrap: break-word; ...

Exploring the potential of Material UI's "sx" prop in combination with computed values

Currently, I am working on a Fab component that changes color when clicked. However, I am facing an issue where the text color can only be modified within the sx property. I am unsure why this conditional cannot be applied inside the sx prop. If I cannot ...

Establish a default route within a Node Express application to handle multiple generic URLs (url/index, url/index2, url/index3, and

Currently, I am in the process of learning React and Express frameworks through exercises provided by NodeSchool.io. My goal is to consolidate all exercise files into a single application with multiple pages named as: index index2 index3 index4 .. ...

Ways to prevent the jQuery simple slider from transitioning slides while it is in an invisible state

There is a jQuery slider on my website that behaves strangely when I navigate away from the Chrome browser and return later. It seems to speed through all pending slides quickly when it was not visible. Now, I want the slider to pause when it becomes invi ...

The useEffect hook in Next.js does not trigger a re-render when the route changes

I'm currently experiencing an issue with a useEffect inside a component that is present in every component. I've implemented some authentication and redirection logic in this component, but I've noticed that when using Next.js links or the b ...

What is the best way to insert images into a div in Ionic framework?

I am facing an issue with fitting an image inside a div container. Here is my code structure: <div style="background-color: red; height: 200px; width: 200px;"> <ion-img src="{{kategori[i].img}}"></ion-img> & ...

Enhance the visual appeal of your checkboxes in React Fluent UI by customizing the color of the checked mark and

I have a React application using Fluent UI. Currently, the <Checkbox/> component is displaying with its default colors and behavior like this: I want to customize the color of the checked mark and label (Green for checked mark and brown for label). ...

Encountering an error in React.js: "Unable to access property 'bind' as it is undefined."

Despite binding this.handleChange = this.handleChange.bind(this); within the constructor function, I am still encountering a "cannot read property undefined" error. Is there any solution to fix this issue? import React, { Component } from "react"; import ...

The menu was intended to be hidden when the mouse is moved away, but it actually hides

I'm facing an issue with my button and menu functionality. Even though I have coded the menu to hide itself when the mouse leaves, it hides before the mouse even goes over it. Any suggestions on how to resolve this? function showMenu() { var menu ...

Is it the correct method to query names within JavaScript arrays?

I am looking to create a dynamic list view using React JS without relying on any pre-built components. My goal is to incorporate a basic search function that can find users by their names, and I need to address this issue... For example, I have drafted th ...

What is the best way to modify a date and time within an <td><input> element using jQuery?

I am looking to automate the updating of the datetime in a <td> tag, but I am struggling with implementing jQuery within tables. I also plan on resetting to the default datetime value if the checkbox is unchecked, although I will attempt to tackle t ...

Encountering obstacles as a novice trying to master CSS styling techniques

I'm having trouble aligning buttons at the center top of the screen. Despite my efforts, I can't seem to get them perfectly aligned https://i.stack.imgur.com/j7Bea.png button { width: 13%; height: 50px; display: inline-block; fo ...

What are some tactics for avoiding movement in the presence of a border setting?

I created a webpage that has the following structure: .topbar-container { width: 100%; position: fixed; top: 0; background-color: #2d3e50; z-index: 999; display: flex; transition: height 500ms; } @media (min-width: 992px) { .topbar-cont ...