Skip to content

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“:


The output is like :


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


and after the above button click:


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

const questions =, index) => {

 return ( 
    <div key = {question.question_id}>   
    {, i) => (
        option.questionID === question.question_id ? //to show only this question's options
              <span>Option {i}:</span>
              <TextField type="text" defaultValue={option.description} />
              <TextField type="number" defaultValue={option.value}/>
              <button onClick={() => this.removeOption(i)}>Remove Option</button>

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


    let options = [...this.state.options_array];
    options.splice(index, 1);
    this.setState({ options_array: options });

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

 return (



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.