GuerillaRadio GuerillaRadio - 11 months ago 39
Javascript Question

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 =;
const newBulletPoint = {
id: += 1,
title: 'Click to add'
const newData = array.splice(this.state.activeBulletPointId, 0, newBulletPoint);
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.

Answer Source

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);

    data: newData
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download