How to Delete individual items from list in react

General Tech Bugs & Fixes . 2 years ago

  0   2   0   0   0 tuteeHUB earn credit +10 pts

5 Star Rating 5 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Write Your Comments or Explanations to Help Others



Tuteehub forum answer Answers (2)


profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I have built a simple ToDo App. Rending the tasks from the form input is working fine, but I am unable to delete the tasks when clicked on Delete button.

export class TodoList extends Component {
  constructor(props) {
    super(props)

    this.state = {
        task:'',
        items:[]
    }
  }
  onChangeHandler=(e)=>{
    this.setState({
        [e.target.name]: e.target.value
    })
  }
  addItem=(e)=>{
    e.preventDefault()
    if (this.state.task!==""){
    this.setState({
        items:[...this.state.items,this.state.task],
        task:''
    })
  }
  }
  removeItem=(index)=>{
    const remainingItems = this.state.items.filter(j => {
      return j !== index
    })
    this.setState({
      items: remainingItems
    })
  };

  render() {
    return (
      <div>
        <form>
            <input type='text' name="task"onChange={this.onChangeHandler} value={this.state.task} placeholder='Enter Task'/>
            <button type='submit' onClick={this.addItem}>Add Taskbutton>
        form>
        <Lists items={this.state.items}
                delete={this.removeItem}/>
      div>
    )
  }
}





export class Lists extends Component {

  removeItems=(index)=>{
    this.props.delete(index)
  }

  render() {
    return (
      <div>
        {this.props
                                                    
                                                    
0 views   0 shares
profilepic.png
manpreet 2 years ago

 

Do you even happen to have any items to delete here or the list comes up empty? Delete function itself looks fine but you have couple of problems here.

  1. Don't use index as a key. In case you're reordering or deleting (which you are doing) an array of items, you can run into a lot of issues. Here's a good article: https://medium.com/@vraa/why-using-an-index-as-key-in-react-is-probably-a-bad-idea-7543de68b17c Probably the error is with this since you're deleting key which, since it's an iterator, is reassigned to another element when array repopulates itself. Change iterator to some other unique identifier for each element.

  2. You're calling removeItems method as soon as it's set. If you have invoked methods (with ()) inside return of render, it will be executed immediately on each refresh. That's why I'm asking do you have anything to delete at all since, if delete function is okay written, this would probably delete all items as soon as they are added.

  3. Best method would be to use dataset. To each element you can add dataset like this:

data-item-id={some-id} and you can fetch it inside your method from the fired event like this const clickedId = event.currentTarget.dataset.someId. Note that dataset in the element must be written like-this, and it's rewritten automatically when fetching it into camelCase (likeThis). Then you can use this index to target the element you want inside the array and delete it.

Note that the iterator issue still applies, and you need a different unique identifier.

Let me know if you need further explanation.


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.

tuteehub community

Join Our Community Today

Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.

tuteehub community