Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  156] [ 5]  / answers: 1 / hits: 30885  / 7 Years ago, tue, july 25, 2017, 12:00:00

I'm trying to use splice to add new components into an array. If I use concat all the elements are added properly at the end, but what I also need is add at the beginning or in the middle of the array using splice. Any suggest ?



class App extends React.Component {
state = {
components: []
};

addNewElement = (element) => {
this.setState(prevState => ({
//Works fine
//components: prevState.components.concat(element)

components: prevState.components.splice(0, 0, element)
}));
};

}

More From » reactjs

 Answers
18

Be careful to note the difference between methods that mutate the array on which they are called and methods which returns mutated versions of the array on which they are called.



prevState.components.splice(0, 0, element) returns a new array containing the elements which have been removed, which for your purposes is going to be nothing.



Notably, splice also mutates the components array; mutating your State elements is A Bad Thing To Do; one simple way to avoid that is to create a clone of your array and splice that.



this.setState(prevState => {
const components = prevState.components.slice(0);
components.splice(0, 0, element);
return { components };
});


This is functional, but relatively inelegant.



Other options you could consider would be to use React's immutability helper or use slice to divide your original array in two then concat all the bits together:



const i = // index at which to insert the new elements
const left = prevState.components.slice(0, i)
const right = prevState.components.slice(i)
return {
components: left.concat(elements, right)
}

[#56976] Friday, July 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keric

Total Points: 572
Total Questions: 93
Total Answers: 97

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;