Search code examples
reactjsreact-hooksreact-bootstrap

Add Column and Rows in React onclick


I am new to React JS and I want to add onClick event to my corner cells of the table. So, onClick I have to add column and row adjacent to the clicked cell.

Table schema

My table initially consists of 4 column and row respectively. And on click of corner edges a column corresponding to it must be added. For example in the image above if I click on A the column and row will be added as shown. How can I do this ?

import { render } from "@testing-library/react";
import React, { useState, useRef } from "react";
import { Table } from "react-bootstrap";

var MyTable = () => {
  let [panel, setPanel] = useState([
    ["S", "O", "L", "A"],
    ["R", "P", "A", "N"],
    ["E", "L", "S", "O"],
    ["L", "A", "R", "R"],
  ]);




  function renderTable() {
    var rows = panel.map(function (item, i) {
      var entry = item.map(function (element, j) {
        return (
          <td id={j}>
            {element}
          </td>
        );
      });
      return <tr id={i}>{entry}</tr>;
    });
    return (
      <Table>
        <tbody>{rows}</tbody>
      </Table>
    );
  }
  return <>{renderTable()}</>;
};

export default MyTable;

My code structure something like shown above.


Solution

  • The solution to your problem is modifying the state when onClicking a cell. When you modify your state panel. It will be rendered in UI as per your renderTable code.

    You can modify that state panel by adding onClick event listener to your td like this -

    return (
       <td id={j} onClick={() => handleRowColAddition(i, j)}>
          {element}
       </td>
    );
    

    And I am passing i, j in the function to identify the row and column of the cell.

    In handleRowColAddition function, add logic to modify your state panel.

    const handleRowColAddition = (i, j) => {
      // For top left cell, i is 0 and j is 0.
      if (i === 0 && j === 0) {
        
        // copying the `panel` value into temporary variable `state`.
        let state = [...panel];
    
        // Adding "0" at the beginning of every row. Note, "0" is for visual purposes. You can add whatever you like.
        state = state.map((row) => {
          return ["0"].concat(row);
        });
    
        // Making a row with 0's filled to insert at top.
        const row = Array(state[0].length).fill("0");
       
        // Appending the made row to insert at top.
        state = [row].concat(state);
    
        // Update the `panel` value with modified value of temporary variable `state`
        setPanel(state);
      }
    };
    

    I have added logic for the top left cell. If user clicks on top left cell, A column to the left and row to the top will be inserted.

    Accordingly, you can add logic for other edge cells.

    Here is the demo of the working solution - https://codesandbox.io/s/modest-smoke-m8liu?file=/src/Table.js