Search code examples
reactjshtml-tablerowdelete-row

How to delete a row from a HTML table with React?


I am trying to delete a row inside a HTML table using React. I have an onClick handler on a delete button inside the row I would like to delete, but how can I target that specfic row to delete? I pass along a site variable with an unique id attribute. Maybe that helps?

// table component

export default function IndexPage() {
  const site = { id: 123 };
  const removeSite = async ({ id, e }) => {
    console.log(e.target);
  };
  return (
    <table>
      <tbody>
        <tr>
          <th>Name</th>
        </tr>
        <tr>
          <td>Valles Caldera National Preserve</td>
          <button onClick={(e) => removeSite(site,e )}>Delete</button>
        </tr>
      </tbody>
    </table>
  );
}

Here is a link to a code sandbox.


Solution

  • The better way to implement this will be to display using an Array and giving ids to individual row items ->

    Your code will be something like this then ->

    const [dataArray, setDataArray] = useState([
        { name: "Valles Caldera National Preserve", id: 1 },
        { name: "Tyler Morales", id: 2 },
      ]);
    
      const removeSite = async (id) => {
        setDataArray((data) => data.filter((dataEach) => dataEach.id !== id));
      };
    
      return (
        <table>
          <tbody>
            <tr>
              <th>Name</th>
            </tr>
            {dataArray.map((data) => (
              <tr key={data.id}>
                <td>{data.name}</td>
                <button onClick={(e) => removeSite(data.id)}>Delete</button>
              </tr>
            ))}
          </tbody>
        </table>
      );