Multiple ways to remove an element from an array in React with code examples
- Admin
- Dec 31, 2023
- Typescript Reactjs
This tutorial explains how to remove an element from an array of elements in React with code examples.
In this section, we will learn how to remove an object from an array of objects in React. ReactJS is a JavaScript UI library for building user interfaces. It is maintained by Facebook and Instagram.
ReactJS remove object element from an array with code examples:
How to remove an object from an array in ReactJS
In this article, I’m going to show you how to remove an object from an array in ReactJS. It’s very easy once you know the syntax. We’ll look at removing a list of items, removing by index, and removing by key.
- Create a new array with the object you want to remove and the rest of the array.
- There are two approaches we can do using javascript in React.
- One way to remove some of them without modifying the original list.
- Another way to remove the element by returning a new array is by excluding an item
Let’s see how we can implement these two approaches with array methods in React
- First way is using the Array filter method to return a new array
In this, the employee array contains a list of objects,
Array.filter method iterates and checks name property is not a specific value and returns the new array with the specified items removed from it.
const employees = [
{ id: 1, name: "john" },
{ id: 2, name: "eric" },
{ id: 3, name: "abc" },
];
const newEmployees = employees.filter((emp) => emp.name !== "john");
This approach does not mutate the original array.
The second approach mutates the array using the splice method This approach mutates the original array and returns the original array by removing an element at a specific position
- Find the element of an array using the indexOf method
- splice🔗 method adds the element to the index position.
var numbers = [1, 2, 3];
var index = myArray.indexOf(2);
numbers.splice(index, 1); // delete 2 and array positions are shifted
console.log(numbers);
Output:
[1, 3];
third way using the Array pop method to remove the last element
The array pop method removes the last element from an array. It mutates the original array
let numbers = [1, 2, 3, 4];
let element = numbers.pop();
console.log(element);
console.log(numbers);
Output:
(4)[(1, 2, 3)];
four-way using the Array shift method to remove the first element
The array shift method removes the first element from an array. It mutates the original array.
let numbers = [1, 2, 3, 4];
let element = numbers.shift();
console.log(element);
console.log(numbers);
Output:
(1)[(1, 2, 3)];
Fifth way using the Array slice method without array mutation
Array slice🔗 method returns elements for the given start and end position and the original array does not modify.
let numbers = [1, 2, 3, 4];
let newNumbers = numbers.slice(2);
console.log(newNumbers);
console.log(numbers);
Output:
[3, 4][(1, 2, 3)];
How to remove an element from an array in React state?
React components maintain the state that contains the array of elements. The below example removes an array of the element from a component state. Created a button to add an element and remove a button for each element to remove the specific element.
Used the splice method to remove a current index element, You can use one of the above five approaches to remove an element from an array.
Finally, update the state after removing an element
Here is an example
import React, { Component } from "react";
import { render } from "react-dom";
class App extends Component {
constructor() {
super();
this.state = {
names: [],
name: "",
};
}
handleChange = (event) => {
this.setState({ name: event.target.value });
};
deleteElement = (index) => {
this.state.names.splice(index, 1);
this.setState({ names: this.state.names });
console.log(index);
};
addElement = () => {
const names = [...this.state.names];
names.push(this.state.name);
this.setState({ names: names });
this.setState({ name: "" });
};
render() {
const print = () => {
return this.state.names.map((item, index) => {
return (
<div key={item}>
<span>{item} </span>
<button onClick={() => this.deleteElement(index)}>Delete</button>
</div>
);
});
};
return (
<div>
<input
type="text"
value={this.state.name}
onChange={this.handleChange}
/>
<button onClick={this.addElement}>Add Element</button>
<h3>List of elements</h3>
{print()}
</div>
);
}
}
render(<App />, document.getElementById("root"));
Conclusion
Learned multiple ways to react components
- Remove an element from an array in React
- Remove an element from the state array in React Component