hpal007
hpal007

Reputation: 313

Dynamic Table in react using material ui

I am having trouble converting below code into reactJs, problem that i am facing this is here Table tag is used and updated based upon number of row/cell, but in react there I dont want to use createElement/appendChild,

I am using useState to get the counts, but than Table tag does not work as expected. Not sure what is way to have this Tag in react or with use of material ui.

link:https://codesandbox.io/s/muddy-bird-qu9bg?file=/src/DataTable.js

function CreateTable() {
    var rowCtr;
    var cellCtr;
    var rowCnt;
    var cellCnt;
    var myTableDiv = document.getElementById("myDynamicTable");
    var table = document.createElement('Table');
    table.setAttribute("contenteditable", "true");
    table.border = '1';
    table.id = 'myTable';
    var tableBody = document.createElement('Tbody');
    table.appendChild(tableBody);
    rowCnt = document.getElementById('txtrows').value;
    cellCnt = document.getElementById('txtcols').value;
    for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
        var tr = document.createElement('tr');
        tableBody.appendChild(tr);
        for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
            var td = document.createElement('td');
            td.width = '120';
            td.appendChild(document.createTextNode("Click me, Row:" + rowCtr + " Column:" + cellCtr));
            tr.appendChild(td);
        }
    }
    myTableDiv.appendChild(table);
    }

<table contenteditable = "true">
    <tr>
        <td>Row Count</td>
        <td>Column Count</td>
        <td></td>
    </tr>
    <tr>
        <td><input type="text" id="txtrows" /></td>
        <td><input type="text" id="txtcols"/></td>
        <td><button onclick="CreateTable()">Create Table</button></td>
    </tr>
</table>



<div id="myDynamicTable"></div>

Upvotes: 1

Views: 7177

Answers (1)

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

You need to make the DataTable.js file like,

import React, { Fragment, useState } from "react";
import Table from "@material-ui/core/Table";
import TableHead from "@material-ui/core/TableHead";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";
import Button from "@material-ui/core/Button";

export default function DataTable() {
  const [rowCount, setRowCount] = useState("");
  const [colCount, setColCount] = useState("");

  const [rowCountArray, setRowCountArray] = useState([]);
  const [colCountArray, setColCountArray] = useState([]);

  const [showTable, setShowTable] = useState(false);

  const CreateTable = () => {
     rowCountArray.length = 0;
     colCountArray.length = 0;

    for (let i = 1; i <= rowCount; i++) {
      rowCountArray.push(i);
    }
    setRowCountArray(rowCountArray);

    for (let i = 1; i <= colCount; i++) {
      colCountArray.push(i);
    }
    setColCountArray(colCountArray);

    setShowTable(true);
  };

  return (
    <>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>Row Count</TableCell>
            <TableCell>Col Count</TableCell>
            <TableCell></TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          <TableRow>
            <TableCell component="th" scope="row">
              <input
                type="text"
                id="txtrows"
                value={rowCount}
                onChange={(e) => setRowCount(e.target.value)}
              />
            </TableCell>
            <TableCell component="th" scope="row">
              <input
                type="text"
                id="txtcols"
                value={colCount}
                onChange={(e) => setColCount(e.target.value)}
              />
            </TableCell>
            <TableCell>
              <Button variant="contained" color="primary" onClick={CreateTable}>
                Create Table
              </Button>
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
      {showTable ? (
        <Table>
          <TableBody>
            {rowCountArray.map((row, index) => (
              <TableRow key={index}>
                {colCountArray.map((col, index) => (
                  <TableCell key={index}>
                    Row {row} - Col {col}
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableBody>
        </Table>
      ) : null}
    </>
  );
}

On click over the Create Table button, you can create a function and generate an array based on the count entered in rowCount and colCount like,

    const CreateTable = () => {

      rowCountArray.length = 0;
      colCountArray.length = 0;

      for (let i = 1; i <= rowCount; i++) {
         rowCountArray.push(i);
      }
      setRowCountArray(rowCountArray);
        
      for (let i = 1; i <= colCount; i++) {
         colCountArray.push(i);
      }
      setColCountArray(colCountArray);
        
     setShowTable(true);
   };

Then using the following method, you can generate the table with respective rows and cols,

{rowCountArray.map((row, index) => (
   <TableRow key={index}>
      {colCountArray.map((col, index) => (
        <TableCell key={index}>
          Row {row} - Col {col}
        </TableCell>
       ))}
   </TableRow>
 ))}

Edit bold-smoke-756so

Upvotes: 1

Related Questions