Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  54] [ 4]  / answers: 1 / hits: 40799  / 7 Years ago, mon, august 14, 2017, 12:00:00

I'm replacing an item in a react state array by using the ... spread syntax. This works:



let newImages = [...this.state.images]
newImages[4] = updatedImage
this.setState({images:newImages})


Would it be possible to do this in one line of code? Something like this? (this doesn't work obviously...)



this.setState({images: [...this.state.images, [4]:updatedImage})

More From » reactjs

 Answers
2

use Array.slice


this.setState({
images: [
...this.state.images.slice(0, 4),
updatedImage,
...this.state.images.slice(5),
],
});

Edit from original post: changed the 3 o a 4 in the second parameter of the slice method since the second parameter points to the member of the array that is beyond the last one kept, it now correctly answers the original question.


[#56775] Friday, August 11, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tiffany

Total Points: 46
Total Questions: 97
Total Answers: 84

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;