Home > database >  how to delete a row in table in reactjs
how to delete a row in table in reactjs

Time:09-04

I'm trying to implement a delete operation on table rows. but it keeps on throwing errors. So I need some help to figure this out.

I don't know to how to set id that can be auto incremented so I gave Date.now(). now what I want is to delete the row that i perform the delete operation on. I'm new to react so sorry for the bad code. thank you in advance.

heres my code

import React from "react";
import { CirclesWithBar } from "react-loader-spinner";
import { useState } from "react";
import Table from "./Table";
function Main() {

  // *****INITIALIZING*****

  const [tableData, setTableData] = useState([])
  const [formInputData, setformInputData] = useState(
    {
      id: Date.now(),
      Name: '',
      email: '',
    }
  );

  const [loading, setloading] = useState(false);

  // const deleteTableRows = (index)=>{
  //      const rows = [...rowsData];
  //      rows.splice(index, 1);
  //      setTableData(rows);
  // }

  // **********DECLARING FUNCTIONS*********


  const handleChange = (evnt) => {
    const newInput = (data) => ({ ...data, id: Date.now(), [evnt.target.name]: evnt.target.value })
    setformInputData(newInput)

  }
  const handleSubmit = (evnt) => {
    evnt.preventDefault();
    setloading(true)

    const checkEmptyInput = !Object.values(formInputData).every(res => res === "")
    if (checkEmptyInput) {
      const newData = (data) => ([...data, formInputData])
      setTableData(newData);
      const emptyInput = { id: '', Name: '', email: '' }
      setformInputData(emptyInput)

    }
    setTimeout(() => {
      setloading(false)

    }, 1000)
  }

  const singleDelete = (event) => {
    event.preventDefault();
    setloading(true)
    const handleDelete = (id) => {
      const newArr = [...tableData];
      console.log(tableData);
      const index = setTableData.findIndex((data) => data.name(id) === id);
      console.log(index);
      newArr.splice(index, 1);
      setTableData(newArr);
    }
    setTimeout(() => {
      setloading(false)

    }, 1000)
  }

  // ************RETURNING VALUES************

  return (
    <div className="container">
      <div className="row">
        <div className="col-sm-8">
          <div className="col">
            <input type="text" onChange={handleChange} value={formInputData.Name} name="Name" className="form-control" placeholder="Name" />
          </div>
          <div className="col">
            <input type="email" onChange={handleChange} value={formInputData.email} name="email" className="form-control" placeholder="Email Address" />
          </div>
          <div className="col">
            <input type="submit" onClick={handleSubmit} className="btn btn-success" />
            {
              loading ?

                <CirclesWithBar
                  height="75"
                  width="100"
                  color="#002B5B"
                  wrapperStyle={{}}
                  wrapperClass=""
                  visible={true}
                  alignSelf='center'
                  outerCircleColor=""
                  innerCircleColor=""
                  barColor=""
                  ariaLabel='circles-with-bar-loading' loading={loading} size={50} />
                :
                <div>
                  {
                    <table className="table" id='table'>
                      <thead>
                        <tr>
                          <th>S.N</th>
                          <th>ID</th>
                          <th>Full Name</th>
                          <th>Email Address</th>
                          <th>Action</th>
                        </tr>
                      </thead>
                      <tbody>
                        {
                          tableData.map((data, index) => {
                            return (
                              <tr>
                                <td>{index   1}</td>
                                <td>{data.id}</td>
                                <td>{data.Name}</td>
                                <td>{data.email}</td>
                                <td><button value={data.id} onClick={() => singleDelete(data.id)} className="btn btn-danger">Delete</button></td>
                              </tr>
                            )
                          })
                        }
                      </tbody>
                    </table>
                  }
                </div>
            }
          </div>
        </div>
      </div>
    </div>
  );
}
export default Main;

CodePudding user response:

First, the error happens because you don't pass the click event parameter to the function.

It should be like that.

(e) => singleDelete(e, data.id)

Second, You can just use filter method to delete the item by add a condition any element that doesn't have this id.

  const singleDelete = (event, id) => {
    event.preventDefault();
    setloading(true);
    setTableData((prev) => prev.filter((i) => i.id !== id));
    setTimeout(() => {
      setloading(false);
    }, 1000);
  };

This is a full example of code.

import React from "react";
import { CirclesWithBar } from "react-loader-spinner";
import { useState } from "react";
function Main() {
  // *****INITIALIZING*****

  const [tableData, setTableData] = useState([]);
  const [formInputData, setformInputData] = useState({
    id: Date.now(),
    Name: "",
    email: ""
  });

  const [loading, setloading] = useState(false);

  // const deleteTableRows = (index)=>{
  //      const rows = [...rowsData];
  //      rows.splice(index, 1);
  //      setTableData(rows);
  // }

  // **********DECLARING FUNCTIONS*********

  const handleChange = (evnt) => {
    const newInput = (data) => ({
      ...data,
      id: Date.now(),
      [evnt.target.name]: evnt.target.value
    });
    setformInputData(newInput);
  };
  const handleSubmit = (evnt) => {
    evnt.preventDefault();
    setloading(true);

    const checkEmptyInput = !Object.values(formInputData).every(
      (res) => res === ""
    );
    if (checkEmptyInput) {
      const newData = (data) => [...data, formInputData];
      setTableData(newData);
      const emptyInput = { id: "", Name: "", email: "" };
      setformInputData(emptyInput);
    }
    setTimeout(() => {
      setloading(false);
    }, 1000);
  };

  const singleDelete = (event, id) => {
    event.preventDefault();
    setloading(true);
    setTableData((prev) => prev.filter((i) => i.id !== id));
    setTimeout(() => {
      setloading(false);
    }, 1000);
  };

  // ************RETURNING VALUES************

  return (
    <div className="container">
      <div className="row">
        <div className="col-sm-8">
          <div className="col">
            <input
              type="text"
              onChange={handleChange}
              value={formInputData.Name}
              name="Name"
              className="form-control"
              placeholder="Name"
            />
          </div>
          <div className="col">
            <input
              type="email"
              onChange={handleChange}
              value={formInputData.email}
              name="email"
              className="form-control"
              placeholder="Email Address"
            />
          </div>
          <div className="col">
            <input
              type="submit"
              onClick={handleSubmit}
              className="btn btn-success"
            />
            {loading ? (
              <CirclesWithBar
                height="75"
                width="100"
                color="#002B5B"
                wrapperStyle={{}}
                wrapperClass=""
                visible={true}
                alignSelf="center"
                outerCircleColor=""
                innerCircleColor=""
                barColor=""
                ariaLabel="circles-with-bar-loading"
                loading={loading}
                size={50}
              />
            ) : (
              <div>
                {
                  <table className="table" id="table">
                    <thead>
                      <tr>
                        <th>S.N</th>
                        <th>ID</th>
                        <th>Full Name</th>
                        <th>Email Address</th>
                        <th>Action</th>
                      </tr>
                    </thead>
                    <tbody>
                      {tableData.map((data, index) => {
                        return (
                          <tr>
                            <td>{index   1}</td>
                            <td>{data.id}</td>
                            <td>{data.Name}</td>
                            <td>{data.email}</td>
                            <td>
                              <button
                                value={data.id}
                                onClick={(e) => singleDelete(e, data.id)}
                                className="btn btn-danger"
                              >
                                Delete
                              </button>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                }
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
export default Main;

This is working example with codesandbox.

CodePudding user response:

Just modify your singleDelete function in this way -

  const singleDelete = (id) => {
    setloading(true);
    
    const newTableData = tableData.filter(item => item.id !== id );
    setTableData(newTableData)

    setTimeout(() => {
      setloading(false)

    }, 1000)
  }
  • Related