'adding item in to react state at certain position related to the item at hand?
How to update state array to add a value after related position rather than at the end of the array ? in the example below for example I want rice to go after rice rather than after bananas ? , this current logic is making thing really mixed when I want to render items according to what the user has selected to be the first item.
let stateArr = [{item : cucumber}, {item : rice }, {item: bannan }, {item : rice }]
// current state logic
[...stateArr, newItem ]
Solution 1:[1]
If you want to keep things immutable, you can slice your array at the point you want to insert the new item, and spread those two slices around your new value.
let stateArr = [
{ item: "cucumber" },
{ item: "rice" },
{ item: "bannan" },
{ item: "fish" },
];
// First, find the location of the item you want to insert _after_
const riceIndex = stateArr.findIndex(({ item }) => item === "rice");
const newItem = { item: "crab" };
// Next, slice _right after_ that item (+ 1)
const newState = [
...stateArr.slice(0, riceIndex + 1),
newItem,
...stateArr.slice(riceIndex + 1),
];
console.log(newState);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | romellem |
