Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append array of values to the current array in a state in React JS

Tags:

reactjs

I have the state values as

this.state = {
    emp: [
        {id: "1", name: "A"}
        {id: "2", name: "B"}
        {id: "3", name: "B"}
    ]
}

How can I add an array like var arr = {id:"4", name:"D"} to the state emp without removing the current values of array. I just want to append the new array of values to the current state array. Can anyone help?

like image 516
Hareesh S Avatar asked Jun 05 '18 09:06

Hareesh S


People also ask

How do you append to state array React?

Use the spread syntax to push an element into a state array in React, e.g. setNames(current => [... current, 'Carl']) . The spread syntax (...) will unpack the existing elements of the state array into a new array where we can add other elements.

How do you add an array to another array in React?

To append one array to another, call the concat() method on the first array, passing it the second array as a parameter, e.g. const arr3 = arr1. concat(arr2) . The concat method will merge the two arrays and will return a new array.

How do you add multiple values in array in React JS?

splice() method to push multiple values to an array, e.g. arr. splice(arr. length, 0, 'b', 'c', 'd'); . The splice() method will add the provided values to the end of the array.

How do you update existing state in React?

To update our state, we use this. setState() and pass in an object. This object will get merged with the current state. When the state has been updated, our component re-renders automatically.


1 Answers

In modern JavaScript you can use the spread operator:

Add a single item

addItem = item => {
  this.setState({
    emp: [
      ...this.state.emp,
      item 
    ]
  })
}

Add multiple items:

addItems = items => {
  this.setState({
    emp: [
      ...this.state.emp,
      ...items
    ]
  })
}

The spread operator places all the elements in this.state.emp in a new array instance and item gets appended as the last element.

You should not mutate a component's state with other means than setState as your rendered data will get out of sync.

like image 139
lipp Avatar answered Sep 19 '22 05:09

lipp