Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splice method in React

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

}
like image 409
Angel Cuenca Avatar asked Sep 18 '26 08:09

Angel Cuenca


1 Answers

splice() returns an array of elements that have been removed from the array. If no elements were removed, splice will return an empty array.

However, splice will change the contents of the array it's called on. You need to set the state on the updated array, not on what splice returns.

Try this method:

addNewElement(element) {
  this.state.components.splice(0, 0, element);
  this.setState({ components: this.state.components });
}

Below is a working snippet to demonstrate how you can insert a new element at a selected index using splice within a React component.

CodePen Demo

like image 112
Dan Kreiger Avatar answered Sep 19 '26 22:09

Dan Kreiger