danielrvt
danielrvt

Reputation: 10926

React prepend item to list

I'm trying to prepend an item to a list:

addPersonHandler = () => {
    const newPerson = {
          id: "new",
          edit: true,        
          name: "",
          dni: "",
          onDelete: this.discardHandler
        };

    // I want to prepend the new person to the people list.
    this.setState({addingPerson: true, people: {[newPerson].concat(this.state.people)});
}

But it ALWAYS renders LAST!

<ul>
    People.map((p, i) => {
      return <li key={p.id}>
        <Person 
          id={p.id} 
          name={p.name} 
          dni={p.dni} 
          onDelete={p.id=="new"? this.discardHandler: this.deleteHandler}
          edit={p.edit}         
          />
      </li>
    });    
</ul>

I really don't know why if I'm adding it to the beginning of the list it is rendering last...

Upvotes: 4

Views: 5115

Answers (4)

zzw
zzw

Reputation: 1

<ul>
          <Person 
          id={p.id} 
          name={p.name} 
          dni={p.dni} 
          onDelete={p.id=="new"? this.discardHandler: this.deleteHandler}
          edit={p.edit}         
          />
    People.map((p, i) => {
      return <li key={p.id}>

      </li>
    });    
</ul>

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30390

Consider the unshift() method, which you can use to prepend one or more elements to the people array.

Keep in mind that unshift() method mutates the array that it's called on:

addPersonHandler = () => {

    const newPerson = {
          id: "new",
          edit: true,        
          name: "",
          dni: "",
          onDelete: this.discardHandler
        };


       // Get people array from current state
       const people = this.state.people;

       // Prepends the newPerson to the start of people array
       people.unshift(newPerson);

       // Return the updated state to your component for re-render
       this.setState({ addingPerson : true, people : people });
}

Upvotes: 2

charlietfl
charlietfl

Reputation: 171700

You can use a spread on original array and remove the {} wrapping new array

this.setState({addingPerson: true, people: [newPerson, ...this.state.people]);

Upvotes: 4

Amruth
Amruth

Reputation: 5912

Try like this, take state in one new array variable and push new object into it, finally update the state.

  addPersonHandler = () => {
      const newPerson = {
        id: "new",
        edit: true,
        name: "",
        dni: "",
        onDelete: this.discardHandler
      };

      let pplArr = this.state.people;
      pplArr.push(newPerson);
      this.setState({ addingPerson: true, people: pplArr });
    };

Upvotes: 0

Related Questions