Skip to content
Advertisement

Removing an object from array with splice() does not work as expected in React

I am creating input fields dynamically based on the number of object in my state array. Beside each field I am adding a button to remove that field. However, when the button is clicked it behaves in an unexpected way.

Below is the visual demonstration:

When I press “Remove Option” button on “Option 0“:

here

The output is like :

this

However, when I see from console.log() the correct object is being removed. These are console.log() outputs before:

before

and after the above button click:

after

Here is how I loop from the array in my render():

JavaScript

Here is my removeOption() method I am using to remove the input fields:

JavaScript

And here is how I am calling it in my render’s return:

JavaScript

Advertisement

Answer

You are missing the keys for the div containers. React needs to know which DOM Element has been removed so it re-renders it. Also, do not use the index of map as the key, instead use something like the id e.g. option.questionID.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement