There are two things to note.
- First of all, we are taking a shallow copy of the array by using
slice() method of javascript. This is done so that
we do not mutate the original state
(Which is a foundational principle in React)
const cartItems = this.state.cartItems.slice(); // We have the copy of original state
The same can we achieved with ES6 spread operator though (which is recommended in React)
const cartItems = [...this.state.cartItems];// This does the same what slice() does
Second part is the logic in filter method which is a Higher Order Function.
cartItems.filter((x)=>x.id!==product.id)
For each item in your array (Which is each object in your array), this callback function runs
(x)=>x.id!==product.id
in each iteration and checks whether item.id (i.e Current Object's id) is not equal to the Id selected. So, All the items are filtered and shown expect for the item where product's id matches the item's id (This one is not shown in DOM) all other.
Finally, you are updating your state with the filtered items and hence your functionality works as expected :)
Would recommend you to learn about Higher Order Functions, such as map(), filter(), reduce() since they are used a lot in React and Javascript frameworks, since you are a just starting.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter