DEV Community

Sattwik Sahu
Sattwik Sahu

Posted on

Why does React not delete the required component but deletes the last sibling?

Here is a similar sandbox. To reproduce the problem:

  1. Create child objects by clicking "+" button
  2. Name the children differently by typing in the textfield
  3. Try to delete a child that is not the last child
  4. Instead of the child which you want to delete, the last child will be deleted

When I try to debug in React DevTools, the element of state.children that I want to delete is deleted, but it still shows up in the front end.
e.g. When there are child nodes with indices 0..4, I press delete on the component with index 2; In React DevTools, the component with index 2 gets deleted, but it deletes component with index 4 in the front-end

Top comments (3)

Collapse
 
ahmedgmurtaza profile image
Ahmed Murtaza • Edited

You should share the codesandbox link, that would be more easy to understand.

By the way, going through your code you can replace splice with filter, as follows:
OLD

 const updatedChildren = [...state.children];
 /* Removes this sub-node's info from
* parent's state.children
*/
 const removedChild = updatedChildren.splice(childIndex, 1);
 updateChildren(updatedChildren);
Enter fullscreen mode Exit fullscreen mode

NEW

const updatedChildren = [...state.children].filter((item,index)=>index !== childIndex);
updateChildren(updatedChildren);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
swagwik profile image
Sattwik Sahu

Thanks, I put i the codesandbox link too. I have already tried both approaches (splice and filter). The problem is that the component's state updates perfectly well in both cases, but the DOM does not.

Example

If I delete element #3 in a list named 1, 2, 3, 4, 5, then the element #3 GETS DELETED on the component STATE when I press delete but on the DOM, element #5 gets deleted instead of #3

Collapse
 
olympus_bros profile image
Kratos_Spartan • Edited

"li" should have unique keys don't use index as unique keys because when react checks when what's different to the old render it cant figure out what changed.
Make a new array with unique keys like 'abcef', 'xyz' , 'hijk' , etc... And use these keys for the every li you have
Then you wont have this issue