0

In my sample todo app, I have created a list of todo items that are stored in an array. In my wrapper List class I render the elements as Items in the array, I have a remove function that I pass as props to the Items and once the items are clicked, they are removed from the array and thus not rendered anymore. The problem that I am having is that when I remove the first element of the array, the second moves up, but the state of the second Item element is set to the state of the deleted first element even when the props of the element are correct.

This is my List element

<div className="tasks-wrap">
                    {this.state.items.map((task, index) => {
                        return (
                            <Item index={index} refreshColor={this.state.refreshColor} ref={this.child} key={index} item={task} remove={this.remove}/>
                    )})}
                </div>

And this is the constructor of the item element

constructor(props) {
        super(props);
        console.log(this.props.index)
        this.state = {dateDue:this.props.item.dateDue, urgency_class:this.refreshColor()};
        this.refreshColor = this.refreshColor.bind(this)

    }

Why is this happening?

Nandha
  • 96
  • 7
  • `key={index}` is to blame. For React to keep track of arrays whose order might change you need to use a unique property of each element in the array (ie. `key={task.id}`), otherwise it just sees an element with the same key in the same position as the last render and doesn't update it. – pilchard Jul 07 '21 at 00:52
  • dev tools should complain about missing key. – Matt Jul 07 '21 at 00:53
  • It has a key, but the OP used index. – pilchard Jul 07 '21 at 00:54
  • Yes, thank you so much. the only problem I see now is that remove now becomes o(n) instead of o(1) – Nandha Jul 07 '21 at 00:59
  • 1
    Delete ***should*** necessarily be an `O(n)` operation in React since you need to return a new array reference. – Drew Reese Jul 07 '21 at 01:13

0 Answers0