Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React list rendering wrong data after deleting item

I have a simple list of student objects with name and their scores in state.

Their name is bound to <b>{student.name}</b> and their score is bound to

<input type="text" defaultValue={student.score}/>

Whenever I want to delete the first student from this list and re-rendering the component by calling set state.

The input tag of the second student showing the score of the first student instead of having its own. Why this happening where I am doing it wrong ??

Here is my code jsbin

class App extends React.Component{
  constructor(){
    super();
    this.state ={
      students:[{name:"A",score:10},{name:"B",score:20},{name:"C",score:30}]
    }
  }
  
  onDelete(index){
    this.state.students.splice(index,1);
    this.setState(this.state);
  }
  
   render(){
     return(
       <div>
         {this.state.students.map((student,index)=>{
              return(
                <div key={index}>
                    <b>{student.name}</b> - <input type="text" defaultValue={student.score}/>
                     <button onClick={this.onDelete.bind(this,index)}>delete</button>
                </div>                
              )
         })}
       </div>
     )
   }
}


ReactDOM.render(<App/>,document.getElementById("main"));
like image 819
manas Avatar asked Apr 26 '17 18:04

manas


1 Answers

It's because you're using key={index} instead of a value unique to the student.

When the array is modified the students after the index removed will have the wrong key and React will not register a key change to rerender with the updated data.

You should instead use something like this...

<div key={student.name}>

assuming that student.name is unique.

like image 200
BradByte Avatar answered Nov 16 '22 00:11

BradByte