Adding New Rows to React Material UI table

Viewed 841

Beginner in React trying to create a simple form where we collect the details of the existing loans from the user. The user needs to fill in the text/select fields and click on the Add button and we need to re-render the UI and display the currently filled out details in the table as a row. I have referred to this (How to insert a new row in Material-UI?) link and tried to implement the same.

Issue:

Whenever I click on the add button the page turns blank.

On the console log of the browser I see this:

Objects are not valid as a React child. If you meant to render a collection of children, use an array instead

Can someone let me know what is it that I doing wrong? I am calling the generateRows() function from within the tag which is causing the issue but not sure how to nail down the issue and make it work. Can someone please help with this?

Question 2:

On the same code I need another clarification of how to do it in React.

In the handleAddon callback I am using document.getElementById() to access the value fields that has already been input by the user.

In whatever examples that I have seen in the internet they seem to be attaching an event handler to the DOM and are getting the value of the input using event.target.value. I understand that those are used whenever you want to get the value of the field which triggered the event.

In my case I have an event handler onClick bound to Add button and once the button is clicked I want to get the values of the text / select fields inside the div "existing-loans" based on the id of each input using document.getElementById(). Is that the right way of doing it?

React Version:

   @material-ui/core : 4.11.3,
   react: 17.0.2,
   react-dom: 17.0.2,
   react-scripts: 4.0.3,

Code Snippet:

import React from 'react'
import { makeStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormHelperText from '@material-ui/core/FormHelperText';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import TextField from '@material-ui/core/TextField';
import MuiPhoneInput from 'material-ui-phone-number';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';

const useStyles = makeStyles((theme) => ({
  formControl: {
    margin: theme.spacing(1),
    minWidth: 120,
  },
  selectEmpty: {
    marginTop: theme.spacing(2),
  },
  textField: {
    marginLeft: theme.spacing(1),
    marginRight: theme.spacing(1),
    width: '25ch',
  },
}));

const ExistingLoanForm = props => {
  const classes = useStyles();
  const [loanbank, setLoanBank] = React.useState('');
  const [loantype, setLoanType] = React.useState('');
  const [loanprogram, setLoanProgram] = React.useState('');
  const [loanrows, setLoanRows] = React.useState([]);

  const handleLoanTypeChange = (event) => {
    setLoanType(event.target.value);
  };

  const handleAddLoan = (event) => {
    var loantype = document.getElementById("loan-type-id")
    var bankname = document.getElementById("loan-bank-name").value
    var loanamount = document.getElementById("loan-amt").value
    var emi = document.getElementById("loan-emi").value
    var loantenure = document.getElementById("loan-tenure").value
    var tenurecompleted = document.getElementById("loan-tenure-completed").value

    const loandetails = {
                         type:loantype,
                         bankname: bankname,
                         loanamount: loanamount,
                         emi:emi,
                         loantenure: loantenure,
                         completed: tenurecompleted,
                        }

    setLoanRows( [...loanrows,loandetails]);
    console.log(loanrows);
    //setLoanProgram(event.target.value);
  };

  const generateRows = () => {
    console.log("Inside generateRows function call")
    return (loanrows.map(row => {
      return (
        <TableRow key={row.type}>
          <TableCell component="th" scope="row">
            {row.type}
          </TableCell>
          <TableCell align="right">{row.bankname}</TableCell>
          <TableCell align="right">{row.loanamount}</TableCell>
          <TableCell align="right">{row.emi}</TableCell>
          <TableCell align="right">{row.loantenure}</TableCell>
          <TableCell align="right">{row.completed}</TableCell>
        </TableRow>
      );
    }))
  }

  const varianttype = "outlined"
  const margintype = "normal"
  const marginvalue = 8

  return (
    <div className="loan-form">
      <h1> Customer Details</h1>
      <MuiPhoneInput
            onlyCountries={['in']}
            defaultCountry='in'
      />

      <TextField
            id="full-name"
            variant={varianttype}
            style={{ margin: {marginvalue} }}
            placeholder="Full Name"
            fullWidth
            className={classes.textField}
            margin={margintype}
            InputLabelProps={{
              shrink: true,
            }}
      />

      <div className="obligations">
        <div className="existing-loans">
          <h1> Existing loans</h1>
          <FormControl className={classes.formControl}>
              <InputLabel id="loan-type-id">Loan Type</InputLabel>
              <Select
                labelId="loan-type-id"
                id="loan-type"
                value={loantype}
                onChange={handleLoanTypeChange}
              >
                <MenuItem value="">
                  <em>None</em>
                </MenuItem>
                <MenuItem value={1}>Personal</MenuItem>
                <MenuItem value={2}>Automobile</MenuItem>
                <MenuItem value={3}>Home</MenuItem>
              </Select>
              <FormHelperText>Select the Type of loan</FormHelperText>
          </FormControl>
          <TextField
                id="loan-bank-name"
                variant={varianttype}
                style={{ margin: {marginvalue} }}
                placeholder="Bank name"
                fullWidth
                className={classes.textField}
                margin={margintype}
                InputLabelProps={{
                  shrink: true,
                }}
          />
          <TextField
                id="loan-amt"
                variant={varianttype}
                style={{ margin: {marginvalue} }}
                placeholder="Loan Amount"
                fullWidth
                className={classes.textField}
                margin={margintype}
                InputLabelProps={{
                  shrink: true,
                }}
          />
          <TextField
                id="loan-emi"
                variant={varianttype}
                style={{ margin: {marginvalue} }}
                placeholder="Loan EMI"
                fullWidth
                className={classes.textField}
                margin={margintype}
                InputLabelProps={{
                  shrink: true,
                }}
          />
          <TextField
                id="loan-tenure"
                variant={varianttype}
                style={{ margin: {marginvalue} }}
                placeholder="Loan Tenure"
                fullWidth
                className={classes.textField}
                margin={margintype}
                InputLabelProps={{
                  shrink: true,
                }}
          />
          <TextField
                id="loan-tenure-completed"
                variant={varianttype}
                style={{ margin: {marginvalue} }}
                placeholder="Loan Tenure Completed"
                fullWidth
                className={classes.textField}
                margin={margintype}
                InputLabelProps={{
                  shrink: true,
                }}
          />
          <div>
            <Button variant="contained" color="primary" onClick={handleAddLoan}>
              Add
            </Button>
          </div>
          <div>
            <TableContainer component={Paper}>
              <Table className={classes.table} size="small" aria-label="a dense table">
                <TableHead>
                  <TableRow>
                    <TableCell>Loan Type</TableCell>
                    <TableCell align="right">Bank Name</TableCell>
                    <TableCell align="right">Loan Amount</TableCell>
                    <TableCell align="right">EMI</TableCell>
                    <TableCell align="right">Loan Total Tenure</TableCell>
                    <TableCell align="right">Tenure Completed</TableCell>
                  </TableRow>
                </TableHead>
                <TableBody>
                  {generateRows()}
                </TableBody>
              </Table>
            </TableContainer>
          </div>
        </div>
      </div>
    </div>
  )
}

export default ExistingLoanForm
0 Answers
Related