SeaWarrior404
SeaWarrior404

Reputation: 4157

How to delete a row in a table using React?

I have a table which is a Table component from Material UI. I fetch data from an API and then display the data in the table. The table updates all rows based on events received from web socket. My requirement is when a row say with ID 10 has one of its row values as Closed, I want to remove that particular row from the table. Im using an array to store the data from API and then using map() to render them in individual rows.

    mapTableData = (TableData) => {
const newTableData = tempTableData.map((item, index) => ({
  ...item,
  Column1: () =>
    <p>
      {item.parameter1}
    </p>,
  Column2: () =>
   ........

When an event arrives on web socket and the value of {item.parameter1} changes to 'Closed' I want to remove that particular row from the table. How do implement this? I tried using conditional check for every column but it just gives me a blank row and wont remove it.

Upvotes: 1

Views: 1668

Answers (1)

bcr
bcr

Reputation: 3811

You can use filter which will iterate over the items twice:

const render = (tableData) => {
    return tableData
        .filter(row => row.id !== 10)
        .map(row => {
            // render logic
        })
}

Or, more efficiently, use reduce:

const render = (tableData) => {
    return tableData
        .reduce((aggr, row) => {
            if (row.id !== 10) {
                const jsx = ''; // some logic
                aggr.push(jsx);
            }

            return aggr;
        }, []);
}

Upvotes: 1

Related Questions