React and Material UI: troubleshooting problems with layout columns

I'm working on a project with three columns and I want to include a column for removing each row. Is it possible to add a "removing" column on the right? If so, how can I go about doing it?

VIEW CODESANDBOX: HERE

const CustomTableRow = ({ row, index, arrayHelpers }) => {
  return (
    <>
      <TableRow
        sx={{
          "th, td": { border: 0 }
        }}
      >
        <TableCell component="th" scope="row">
          <FastField
            name={`rows.${index}.attribute`}
            component={TextField}
            fullWidth
          />
        </TableCell>
        <TableCell>
          <FastField
            name={`rows.${index}.ruleId`}
            component={TextField}
            fullWidth
          />
        </TableCell>
      </TableRow>
      <TableRow>
        <TableCell colSpan={2}>
          <FastField
            name={`rows.${index}.thirdRow`}
            component={TextField}
            fullWidth
          />
        </TableCell>
      </TableRow>
      {/* <TableCell align="right">
        <IconButton
          aria-label="delete"
          onClick={() => arrayHelpers.remove(index)}
          size="small"
        >
          <RemoveCircleOutlineIcon sx={{ fontSize: "1.25rem" }} />
        </IconButton>
      </TableCell> */}
    </>
  );
};

Answer №1

Starting off with a rough draft, consider adjusting the row layout to take up 5 columns of space - allocate 4 for the row data/fields and 1 for the removal button. Feel free to customize the column spans as needed to enhance the user interface.

Data Table

<Table sx={{ minWidth: 650 }} aria-label="simple table">
  <TableHead>
    <TableRow
      sx={{
        th: { border: 0 }
      }}
    >
      <TableCell colSpan={2}>Attribute</TableCell>
      <TableCell colSpan={2}>Rule ID</TableCell>
      <TableCell />
    </TableRow>
    <TableRow>
      <TableCell colSpan={4}>Third Row</TableCell>
      <TableCell />
    </TableRow>
  </TableHead>
  <TableBody>
    {values.rows?.map((row, index) => (
      <CustomTableRow
        key={row.id}
        row={row}
        index={index}
        arrayHelpers={arrayHelpers}
      />
    ))}
  </TableBody>
</Table>

Custom Data Viewer

const CustomTableRow = ({ row, index, arrayHelpers }) => {
  return (
    <>
      <TableRow
        sx={{
          "th, td": { border: 0 }
        }}
      >
        <TableCell colSpan={2} component="th" scope="row">
          <FastField
            name={`rows.${index}.attribute`}
            component={TextField}
            fullWidth
          />
        </TableCell>
        <TableCell colSpan={2}>
          <FastField
            name={`rows.${index}.ruleId`}
            component={TextField}
            fullWidth
          />
        </TableCell>
        <TableCell align="center" colSpan={1} rowSpan={2}>
          <IconButton
            aria-label="delete"
            onClick={() => arrayHelpers.remove(index)}
            size="small"
          >
            <RemoveCircleOutlineIcon sx={{ fontSize: "1.25rem" }} />
          </IconButton>
        </TableCell>
      </TableRow>
      <TableRow
        sx={{
          "th, td": { border: 0 }
        }}
      >
        <TableCell colSpan={4}>
          <FastField
            name={`rows.${index}.thirdRow`}
            component={TextField}
            fullWidth
          />
        </TableCell>
      </TableRow>
    </>
  );
};

https://i.stack.imgur.com/FrXIB.png

Answer №2

I have successfully resolved the Column issue, and I believe this solution will benefit you as well. Please review the updated file below:

demo.js

    import React from "react";
    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 Paper from "@mui/material/Paper";
    import { Box, Button } from "@mui/material";
    import AddIcon from "@mui/icons-material/Add";
    import { FieldArray, Form, Formik } from "formik";
    import CustomTableRow from "./CustomTableRow";
    
    const CustomTable = () => {
      const handleSubmit = () => {};
    
      return (
        <TableContainer component={Paper}>
          <Formik
            initialValues={[
              {
                id: 1,
                attribute: "",
                ruleId: "",
                thirdRow: ""
              }
            ]}
            onSubmit={handleSubmit}
          >
            {({ values }) => (
              <Form>
                <FieldArray
                  name="rows"
                  render={(arrayHelpers) => (
                    <React.Fragment>
                      <Box>
                        <Button
                          variant="contained"
                          type="submit"
                          startIcon={<AddIcon />}
                          onClick={() =>
                            arrayHelpers.unshift({
                              id: Date.now(),
                              attribute: "",
                              ruleId: "",
                              thirdRow: ""
                            })
                          }
                        >
                          Add New
                        </Button>
                      </Box>
                      <Table sx={{ minWidth: 650 }} aria-label="simple table">
                        <TableHead>
                          <TableRow
                            sx={{
                              th: { border: 0 }
                            }}
                          >
                            <TableCell>Attribute</TableCell>
                            <TableCell>Rule ID</TableCell>
                            <TableCell colSpan={2}>Actions</TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          {values.rows?.map((row, index) => (
                            <CustomTableRow
                              key={row.id}
                              row={row}
                              index={index}
                              arrayHelpers={arrayHelpers}
                            />
                          ))}
                        </TableBody>
                      </Table>
                    </React.Fragment>
                  )}
                />
              </Form>
            )}
          </Formik>
        </TableContainer>
      );
    };
    
    export default CustomTable;

CustomTableRow.js

    import { TableCell, TableRow, TextField, IconButton } from "@mui/material";
    import { FastField } from "formik";
    import RemoveCircleOutlineIcon from "@mui/icons-material/RemoveCircleOutline";
    import { Button } from "@mui/material";
    const CustomTableRow = ({ row, index, arrayHelpers }) => {
      return (
        <>
          <TableRow
            sx={{
              "th, td": { border: 0 }
            }}
          >
            <TableCell component="th" scope="row">
              <FastField
                name={`rows.${index}.attribute`}
                component={TextField}
                fullWidth
              />
            </TableCell>
            <TableCell>
              <FastField
                name={`rows.${index}.ruleId`}
                component={TextField}
                fullWidth
              />
            </TableCell>
            <TableCell>
              <FastField
                name={`rows.${index}.ruleId`}
                component={TextField}
                fullWidth
              />
            </TableCell>
          </TableRow>
        </>
      );
    };
    
    CustomTableRow.displayName = "CustomTableRow";
    
    export default CustomTableRow;

Answer №3

Double-check your imports to ensure all necessary Material UI components are loaded, especially the Grid component for organizing columns.

Review your code to confirm that the Props and Syntax for the Grid component are correct, ensuring that the xs, sm, md, lg, and xl props add up to 12 as the Grid component follows a 12-column layout.

import { Grid } from '@material-ui/core';
    
    function App() {
      return (
        <Grid container spacing={2}>
          <Grid item xs={12} md={6}>
            {/* Content for left column */}
          </Grid>
          <Grid item xs={12} md={6}>
            {/* Content for right column */}
          </Grid>
        </Grid>
      );
    }

Avoid any CSS styles that may clash with Material UI designs by checking for conflicts. Also, be mindful of the total cost-effective date when working on your project.

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

Guide: Previewing uploaded images with HTML and jQuery, including file names

Any constructive criticism and alternative methods for accomplishing this task are welcomed. I am currently working on writing jQuery code that will allow users to preview file(s) without reloading the DOM. To achieve this, I have been using .append() to ...

Is there a way to send a prop to react-confirm-alert component?

Utilizing react-confirm-alert (https://www.npmjs.com/package/react-confirm-alert) in conjunction with a React component has presented me with a challenge. I am currently able to trigger the confirm alert successfully, display a static message, and delete a ...

Customize the serialization of a single object in Newtonsoft.Json

When comparing hashes of serialized objects on the server and client, it is important for the JSON rendering to be identical on both sides. Currently, there is an issue with a number field being serialized differently in JavaScript and .NET - causing the h ...

Preserving input data based on click and change events

Upon form submission, I encounter an issue with displaying only the divs that contain fields with saved values. The form saves user-entered values using PHP, where some of the fields are initially hidden within div elements until an onclick or onchange eve ...

My div is currently being concealed by a jQuery script that is hiding all of its

Below is the current code snippet: jQuery(document).ready(function($) { $("ul.accordion-section-content li[id*='layers-builder'] button.add-new-widget").click(function() { $("#available-widgets-list div:not([id*='layers-widget']) ...

Employ the setInterval function to run a task every 15 minutes for a total of

I have a task that requires me to use setInterval function 5 times every 15 minutes, totaling one hour of work. Each value retrieved needs to be displayed in an HTML table. Below is the table: enter image description here For example, if it is 7:58 p.m. ...

How to Delete the Bottom Border on Selected Tabs in MUI Using React

I am attempting to customize the appearance of MUI Tabs to achieve a design similar to the image below: https://i.sstatic.net/tBS1K.png I have created a sample code example in a codesandbox environment. You can view it here: Codesandbox Example. In this e ...

What to do when VueJs computed method throws an error: "Cannot access property 'words' of undefined"?

Here is some pseudo code that I've written: var vm = new Vue({ el: '#test', data: { words: [{name:'1'}, {name:'2'}, {name:'3'},{name:'4'},{name:'5'},{name:'6'}], } ...

InvalidSelectorError: The specified selector is not valid //button[contains(., 'buttonText')] while running JavaScript code

Here's an example of HTML code that I am working with: <button id="toolbar-item-17-update-id" type="submit" name="action" value="update" class="button-action-update btn btn-secondary"> Ed ...

I am having difficulty aligning the vertical touch event owl carousel

Here is the link: "jsfiddle.net/nLJ79/". Can you try to find a solution to make the owl carousel vertical? ...

Having trouble sending the welcome message?

Upon someone's entry, an error message Cannot read properties of undefined (reading 'send') is popping up in the console. I have ensured that all the necessary intents are selected for a proper welcome system or message display. Even when I ...

How can you determine if a polymer element has been loaded or not?

element, I am interested in dynamically importing elements using the Polymer.import( elements, callback ) method. The callback is triggered only if the elements have not been imported yet, indicating they are already loaded. My query is: Is there a conve ...

What is the best way to transmit data from a ReactJS form to my API and save it to my database?

I'm facing a challenge with my nodejs expressjs api server and reactjs frontend server. I have set up different routes for creating and posting various items, but I'm struggling to grasp the process of sending user input data from my frontend for ...

Ways to incorporate a while loop into a randomizing function

I've been diving into JavaScript and managed to create a website that displays random gifs when clicked from an array. Now, my goal is to implement a while loop to prevent duplicate images from being shown consecutively. However, I seem to be facing ...

Next.js continues to generate a 404 error page instead of displaying the details of the blog post

I am having trouble with generating my blog details page as I keep getting a 404 error. The data is being fetched from a headless cms called contentful. Below is the structure of my files and code: https://i.stack.imgur.com/kK8B6.png Additionally, here i ...

Is it possible for React Server Side rendering to be re-rendered on the client side?

In this demonstration of isomorphic rendering found at https://github.com/DavidWells/isomorphic-react-example, the author showcases Server Side Rendering by disabling Javascript. However, if JavaScript is enabled on the frontend, does it trigger a re-rende ...

Sending an Angular $http post request to a MVC action but the parameter is coming through as

After posting this content: $http.post(Common.blog.save, { blog: blog }) .then(saveBlogComplete) .catch(function(message) { }); The Fiddler output I receive is as follows: {"blog":{"title":"Chicken Is Good","content":"#Chicken Is Good\ ...

Is there a way to verify if the jcrop widget (copping area) has been successfully initialized?

I am currently utilizing the library . This library provides four handlers to detect when a crop is activated, updated, changed, or removed. My task now is to determine when the cropping widget was initially created. However, I have noticed that there is ...

Clicking the button will remove any previously applied CSS style using jQuery

Is there a way to remove the background color that was applied to a previously clicked button when clicking on another button? The current code successfully changes the background color of the clicked button upon hover, but it doesn't reset or remove ...

React: Material UI causing an error due to an invalid hook call

Working on a React project using create-react-app with material UI, encountering errors like: https://i.stack.imgur.com/mhjkE.png Appears to be an internal issue with material UI once setting a custom theme. import { ThemeProvider } from "@mui/material/ ...