How to remove an element from an array in ReactJS component


In this tutorial, how do remove an element from an array in reactjs application.

It also explains about list of array items in in the browsers where each list has button to remove an item

Other versions available:

Remove object from using index with array splice method

splice is an method in array used to return an new array from the starting array index + optional count of arrays to be removed This modifies an original array and react stores the data in State object, so you have to update the data to State object using setState() expression syntax explained below

Note: This method does mutates the original array, and returns new an array by removing object.

let array = [1, 2, 3, 4, 5]
console.log(array.splice(1)); // [ 2, 3, 4,5 ]
console.log(array); // [ 1 ]

let array1 = [1, 2, 3, 4, 5]
console.log(array1.splice(2)); // [3, 4, 5]
console.log(array1); // [ 1,2]

**splice method **accepts index parameter of an array, It removes an original array and return new array.

If you know the index of an array, This approach is good way.

Let us see an example to remove an object from array from react state object.

  • First create a react component as follows

    class ListComponent extends Component {
      render() {
          return (
            <div className="App">
                 
            </div>
        );
    }
    }
    
  • Usually in real time applications, Data is coming from Backend and holds in the variables

  • In this example, Defined an array of objects assuming there is no backend

  • Initialized state object with API data in the constructor

  • In render method, Iterated objects using .map((item, index) syntax in the list with each item has delete button

  • Delete button has a onClick event bounded to event handler which delete an object from array

    This event handler has been defined with array functions in ES6

      <input type="button" value="Delete" onClick={() => this.onDeleteByIndex(index)} />
    

    The same can be called with old way in ES5 is as follows

        <input type="button" value="Delete" onClick={this.onDeleteByIndex.bind(this,index)} />
    

And the onDeleteByIndex function has - has index of an object which button has been clicked - Copy the data from state object using ES6 … spread operator - splice method removed the object from an array from starting position - update the state object with new array

    onDeleteByIndex = (index) => {
        const newCountries = [...this.state.countries];
        newCountries.splice(index, 1);

        this.setState(state => ({
            countries: newCountries
        }));

Here is complete example includes complete template and JavaScript code

import React, { Component } from "react";
const countriesAPIData = [
    {
        id: 'IND',
        name: 'INDIA'

    },
    {
        id: 'USA',
        name: 'United States of America',

    },
    {
        id: 'CA',
        name: 'CANADA',

    },
    {
        id: 'SG',
        name: 'Singapore',

    }
];
class ListComponent extends Component {
    constructor(props) {

        super(props);
        this.state = {
            countries: countriesAPIData,
        }
    }

    onDeleteByIndex = (index) => {
        const newCountries = [...this.state.countries];
        newCountries.splice(index, 1);

        this.setState(state => ({
            countries: newCountries
        }));
    }

    render() {
        return (
            <div className="App">
                <ul>
                    {this.state.countries.map((item, index) => (
                        <li key={item.id}>
                            <span>{item.name}  </span>
                            <input type="button" value="Delete" onClick={() => this.onDeleteByIndex(index)} />

                        </li>
                    ))}
                </ul>
            </div>
        );
    }
}

export default ListComponent;

And the output displayed in browser

Remove an object from array in reactjs

Delete object from Array using array filter method

THis approach is suitable,if you know the object or index or value to be removed from an array.

Array filter method is used to filter the array with given object and returns an array

filter method in ES5 syntax to remove an elements from array

let array = [1, 2, 3, 4, 5]
let newarray = array.filter(function(element) {
    return element != 2
});
console.log(newarray); // [ 1, 3, 4, 5 ]
console.log(array); // [ 1, 2, 3, 4, 5 ]

The same can be rewritten using ES6 syntax using arrow functions

let array = [1, 2, 3, 4, 5]
let newarray = array.filter(element => element !== 2);
console.log(newarray); // [ 1, 3, 4, 5 ]
console.log(array); // [ 1, 2, 3, 4, 5 ]

In React, filtered the array with removed element and update the state object

    onDeleteObject = (country) => {
        const newCountries = this.state.countries.filter(element => element.id !== country.id);
        this.setState({ countries: newCountries });

    }

Conclusion

On this blog post, You learned how to remove an object from array and update state object with

  • splice method

  • array filter

    splice method mutates the original array and filter does not mutates the original array.

    Finally, based on your needs, you can choose approach.

THE BEST NEWSLETTER ANYWHERE
Join 90,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts