0

I am making something in the following picture:

enter image description here

I wrote the following code:

{ persons.map((person) => <li key = {person.id}> 
  <Person name={person.name} number={person.number}/> 
  <Button text={'Delete'} handler={deleteHandler} /> 
</li>) }

The problem I am facing is, How to make the button (deleteHandler) work and delete the contact associated with it?

What I think should be done -> find out the key associated (key in < li>) with the button and delete it from the array. But then How do I find the key of < li> associated with the button?

Note - I am using React hooks for state changes (NOT the classes), so, please suggest the answer accordingly.

Thanks

4 Answers 4

1
{ persons.map((person) => <li key = {person.id}> 
  <Person name={person.name} number={person.number}/> 
  <Button text={'Delete'} handler={() => deleteHandler(person.id)} /> 
</li>) }

In your handler you can filter your array using person.id

Sign up to request clarification or add additional context in comments.

Comments

1

You can pass particular id or object to delete inside that function

{ persons.map((person) => <li key = {person.id}> 
  <Person name={person.name} number={person.number}/> 
  <Button text={'Delete'} handler={() => deleteHandler(person.id)} /> 
</li>) }

Assuming that you have

const [persons, setPerson] = React.useState([......]);

const deleteHandler = item =>{
 let filtered  = persons.filter(person=> person.id!==item.id);
 setPerson(filtered)
}

Comments

1

First Add Persons to state data like

this.setState( {persons:persons}); 

Then you can use the below code for delete operation

deleteHandler = (person) => {
  this.setState( { persons :  this.state.persons.filter(function( obj ) {
    return obj.id !== person.id;
    })
  });
}


this.state.persons.map((person, index) => {

  return(
        <li key = {person.id}> 
        <Person name={person.name} number={person.number}/> 
        <Button text={'Delete'} handler={()=>{this.deleteHandler(person)}} /> 
        </li>
  )
})

Comments

1

You can either pass the key and check the key to find the index to delete an item or pass the index to deleteHandler() function directly from click handler

{ persons.map((person, i) => <li key = {person.id}> 
  <Person name={person.name} number={person.number}/> 
  <Button text={'Delete'} handler={deleteHandler(i)} /> 
</li>) }

the function should be

const deleteHandler = (index) => {
  persons.splice(index, 1);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.