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 = this.state.values_array.map((question, index) => {
return (
<div key = {question.question_id}>
{this.state.options_array.map((option, i) => (
option.questionID === question.question_id ? //to show only this question's options
<div>
<span>Option {i}:</span>
<TextField type="text" defaultValue={option.description} />
<span>Value:</span>
<TextField type="number" defaultValue={option.value}/>
<button onClick={() => this.removeOption(i)}>Remove Option</button>
</div>
:
null
))}
</div>
)
}
Here is my removeOption()
method I am using to remove the input fields:
removeOption(index){
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 (
<div>{questions}</div>
)
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
.