Home > OS >  Removing element from table reactjs
Removing element from table reactjs

Time:08-24

I have created the table and I have different types of elements that I want to add. After adding the element I want the option to delete one specific element by clicking on the remove button.

import * as React from 'react';
import { useState } from 'react'; 
import { Table } from 'reactstrap';
import { Button } from 'reactstrap';

export default function App() {
 let [myArray, updateMyArray] = useState([]);

 function addElement() {
 updateMyArray((arr) => [
  ...arr,
  <Element value={myArray.length} handleDelete={handleDelete} />,
 ]);
}

const handleDelete = (index, e) => {
updateMyArray(myArray.filter((item) => item.value !== e.target.value));
};

return (
<div>
  <Button onClick={addElement}>Add Element</Button>
  <Table>
    <thead>
      <tr>
        <th>#</th>
        <th>Name</th>
        <th></th>
      </tr>
    </thead>
    <tbody>{myArray}</tbody>
  </Table>
</div>
);
}

function Element({ value, handleDelete }) {
return (
  <tr>
  <td>{value}</td>
  <td>Test</td>
  <td>
    <Button onClick={(e) => handleDelete(value, e)}>Remove Element</Button>
  </td>
</tr>
);
}

With this code snippet, I have an option to create as many elements as I want. But if I create, let's say 10 elements, and I want to delete the 5th element, one cannot delete only that element, but all elements added after the 5th element is created. I am new at the react therefore I cannot realize what causes this problem.

The link for the code: https://stackblitz.com/edit/react-ts-7mwhmw?file=App.tsx

CodePudding user response:

You should create unique index each element of array and dont store component as @Chrisg mentioned.

solution:

let [myArray, updateMyArray] = useState([]);

  function addElement(value) {
    updateMyArray((arr) => [...arr,value]);
  }

  const handleDelete = (index) => {
    updateMyArray(myArray.filter((item,i) => index !== i));
  };

  return (
    <div>
      <Button onClick={() => addElement("newElement")}>Add Element</Button>
      <Table>
        <thead>
          <tr>
            <th>#</th>
            <th>Name</th>
            <th></th>
          </tr>
        </thead>
        <tbody>{myArray.map((item,index) => {
          return <tr>
          <td>{item} {index}</td>
          <td>Test</td>
          <td>
            <Button onClick={() => handleDelete(index, item)}>Remove Element</Button>
          </td>
        </tr>
        })}</tbody>
      </Table>
    </div>
  );

link : https://stackblitz.com/edit/react-ts-wqsmfq?file=App.tsx

  • Related