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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With