Home > Mobile >  how this specific code removes item from list
how this specific code removes item from list

Time:11-17

I'm trying to learn to react online and I understood everything except this line code

const removeItem = (id) => {
    let newPeople = people.filter((person) => person.id !== id);

    setPeople(newPeople);

  };

especially how person.id !== idremoves the item from list and add to new list

here is the full code

import React from 'react';
import { data } from '../../../data';
const UseStateArray = () => {
  const [people, setPeople] = React.useState(data);

  const removeItem = (id) => {
    let newPeople = people.filter((person) => person.id !== id);

    setPeople(newPeople);

  };
  return (
    <>
      {people.map((person) => {
        const { id, name } = person;
        return (
          <div key={id} className='item'>
            <h4>{name}</h4>
            <button onClick={() => removeItem(id)}>remove</button>
          </div>
        );
      })}
      <button className='btn' onClick={() => setPeople([])}>
        clear items
      </button>
    </>
  );
};

export default UseStateArray;

CodePudding user response:

first you shold khow how filter works,

The filter() method creates a new array filled with elements that pass a test provided by a function.

in your case test is person.id !== id, if test passed for an element that element will be in new array. otherwise element will not be in new array. is it clear?

CodePudding user response:

The filter method creates a shallow copy of an array but not the whole array but only those elements that fulfills the predicate.

So newPeople will contain a copy of all the elements within people that it's people[element].id is different than id.

Visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter for additional details of filter method.

  • Related