Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
I cant delete list from react function component

I am practicing react now and I face a problem in react function component with useState. And I can't delete one from the list by clicking the paragraph. Please tell me how should I do. I have no problems with setState but I wanna try this with functional components

import './style.css';
import Person from './Person/Person';

const App = (props) => {
  const [personArray, setPersonArray] = useState({
    person: [
      { name: 'mg mg', age: 20 },
      { name: 'justin', age: 17 },
      { name: 'helen', age: 12 },
    ],
    showPerson: false,
  });

  const showNameHandler = () => {
    const doesShow = personArray.showPerson;
    setPersonArray({
      person: [
        { name: 'mg mg', age: 20 },
        { name: 'justin', age: 17 },
        { name: 'helen', age: 12 },
      ],
      showPerson: !doesShow,
    });
  };

  const deletPerson = (personIndex) => {
    const person = [...personArray.person];
    person.slice(personIndex, 1);
    setPersonArray({ person: person });
  };
  let persons = null;
  if (personArray.showPerson) {
    persons = (
      <div>
        {personArray.person.map((pp, index) => {
          return (
            <Person click={() => deletPerson(index)} name={pp.name} age={pp.age} />
          );
        })}
      </div>
    );
  }
  return (
    <div>
      <div className="wrapper">
        <h1>Hello React</h1>

        {persons}

        <button onClick={showNameHandler}>
          Show Name
        </button>
      </div>
    </div>
  );
};

export default App;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You probably meant to use splice() instead of slice().

const person = [...personArray.person];
person.splice(personIndex, 1);
about 4 years ago · Juan Pablo Isaza Report

0

Use filter instead of slice. And you should set the whole state (person and showPerson properties)

const deletPerson = (personIndex) => {
    const person = personArray.person.filter((elem, index) => {
       return personIndex !== index;
    });
    setPersonArray({ ...personArray, person });
};

https://www.w3schools.com/jsref/jsref_filter.asp

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!