How to remove Object from Array based on ID in react?

Viewed 842

I have a simple React app that populates table based on input. It mimics employee management app but on the most basic level.

I have three components.

In App.js I just render Table component.

Table component has state for handling employees.

  const [employeeData, setEmployeeData] = useState([]);

  const addRow = (data) => {
    const updatedTotalEmployees = [...employeeData];
    updatedTotalEmployees.push(data);
    setEmployeeData(updatedTotalEmployees);
  };

Then I map it in the <tr> and <td> parts of table.

Here I am rendering Form component and passing props to it

  <InputContainer addRow={addRow} />

I have third component that handles form that I pass props from Table component to it.


  const [id, setId] = useState("");
  const [firstName, setFirstName] = useState("");
  const [lastName, setLastName] = useState("");
  // const [deleteId, setDeleteId] = useState("");

  const handleAdding = (e) => {
    e.preventDefault();
    const employee = { id, firstName, lastName };
    addRow(employee);
  };

And on every input I have onChange based on state. For example:

 onChange={(e) => setFirstName(e.target.value)}

In this component, as you can see by the state I have three input fields for adding it's value to the table.

I have fourth input field and the button that I want to use to delete Employee from the table based on ID. So I will type ID in the input field and if that ID is present in the table I want to remove that employee from the table on the click of the button.

I guess I have to have another state for fourth input field, but I am not sure how I would go about deleting from table based on ID. Do I use .filter() method or some other? Or do I target object index?

Do I have logic for deleting row in Table component then have logic for handling form for deletion in InputContainer component.

Here is the sandbox link:

https://codesandbox.io/s/ecstatic-vaughan-6nbe8p?file=/src/InputContainer.js

1 Answers

Your question is not clear. would be great if you could provide a codesandbox link.

From what I understood, first, since you are using state to store employee data, you can add employee data with the following way.

  const addRow = (data) => {   
 setEmployeeData(previousEmployeeData => [...previousEmployeeData, data]);
  };

And you can remove a selected index from the state simply by using filter method as follow

setEmployeeData(previousEmployeeData => previousEmployeeData.filter(data)=> data.id != employeeId )

Here I'm referring employeeId to the id which you want to delete

Related