Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert object into array at specific index in React

I'm attempting to add an object at a specific point in my 'data' array which is this components state. The following isn't working, the array simply gets emptied.

addNewBulletAfterActive = () => {
    const array = this.state.data;
    const newBulletPoint = {
        id: this.state.data.length += 1,
        title: 'Click to add'
    };
    const newData = array.splice(this.state.activeBulletPointId, 0, newBulletPoint);
    this.setState({
        data: newData
    });
}

The idea is that if I have a list of 10 bullet points, the user can click on the 4th bullet point and press enter to add a new bullet point directly after. I've not had any issues adding items to the end of the array but it looks like .splice is causing issues.

like image 601
GuerillaRadio Avatar asked Jul 17 '17 14:07

GuerillaRadio


People also ask

How do you add an element to an array in 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.

Can we use array index as a key in React?

Prevent usage of Array index in keys (react/no-array-index-key) Warn if an element uses an Array index in its key . The key is used by React to identify which items have changed, are added, or are removed and should be stable. It's a bad idea to use the array index since it doesn't uniquely identify your elements.


2 Answers

I believe this should do what you're after.

function addAfter(array, index, newItem) {
    return [
        ...array.slice(0, index),
        newItem,
        ...array.slice(index)
    ];
}

This function returns a new array with a new item inserted in the middle. It doesn't mutate your original array and so will play nicely with component's state and Redux.

You can then assign the output from this function to your state.

like image 156
Aron Avatar answered Oct 19 '22 23:10

Aron


splice returns spliced items (which is empty since you splice 0 items) and mutates original array.

const newData = array.slice(0); // copy

newData.splice(this.state.activeBulletPointId, 0, newBulletPoint);

this.setState({
    data: newData
});
like image 33
Yury Tarabanko Avatar answered Oct 19 '22 23:10

Yury Tarabanko