Cannot delete Item from Todo-list in React

Viewed 841

I have created a simple Todo list, adding item works but when I clicked on the 'delete' button, my Item is not deleting any item from the List. I would like to know what mistakes I am making in my code, Would appreciate all the help I could get. Thanks in Advance! And ofcourse, I have tried Looking through google and Youtube, But just couldnot find the answer I am looking for.

Link: https://codesandbox.io/embed/simple-todolist-react-2019oct-edbjf

App.js:

import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
import TodoForm from "./TodoForm";
import Title from "./Title";

class App extends React.Component {
 // myRef = React.createRef();

  render() {
    return (
      <div className="App">
        <Title />
        <TodoForm />


      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


----------------------
TodoForm.js:

import React from "react";
import ListItems from "./ListItems";

class TodoForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "",
      items: [],
      id: 0
    };
  }

  inputValue = e => {
    this.setState({ value: e.target.value });
  };

  onSubmit = e => {
    e.preventDefault();
    this.setState({
      value: "",
      id: 0,
      items: [...this.state.items, this.state.value]
    });
  };

  deleteItem = (itemTobeDeleted, index) => {
    console.log("itemTobeDeleted:", itemTobeDeleted);
    const filteredItem = this.state.items.filter(item => {
      return item !== itemTobeDeleted;
    });
    this.setState({
      items: filteredItem
    });
  };

  // remove = () => {
  //   console.log("removed me");
  // };

  render() {
    // console.log(this.deleteItem);
    console.log(this.state.items);
    return (
      <div>
        <form onSubmit={this.onSubmit}>
          <input
            type="text"
            placeholder="Enter task"
            value={this.state.value}
            onChange={this.inputValue}
          />

          <button>Add Item</button>
        </form>

        <ListItems items={this.state.items} delete={() => this.deleteItem} />
      </div>
    );
  }
}

export default TodoForm;


----------------------
ListItems.js

import React from "react";

const ListItems = props => (
  <div>
    <ul>
      {props.items.map((item, index) => {
        return (
          <li key={index}>
            {" "}
            {item}
            <button onClick={props.delete(item)}>Delete</button>
          </li>
        );
      })}
    </ul>
  </div>
);

export default ListItems;

enter image description here

4 Answers

The problem is, you must pass a function to the onDelete, but you are directly calling the function

updating the delete item like so,

deleteItem = (itemTobeDeleted, index) => (event) => {

and update this line, (since the itemTobeDeleted was not reaching back to the method)

 <ListItems items={this.state.items} delete={(item) => this.deleteItem(item)} />

fixes the issue

Working sandbox : https://codesandbox.io/s/simple-todolist-react-2019oct-zt5w6

Your solution is close; there are two fixes needed for your app to work as expected.

First, when rendering the ListItems component, ensure that the item is passed through to your deleteItem() function:

<ListItems items={this.state.items} delete={(item) => this.deleteItem(item)} />

Next, your ListItems component needs to be updated so that the delete callback prop is called after an onclick is invoked by a user (rather than immediatly during rendering of that component). This can be fixed by doing the following:

{ props.items.map((item, index) => { 
    return (<li key={index}>{item}
      {/* 
        onClick is specified via inline callback arrow function, and 
        current item is passed to the delete callback prop 
      */}
        <button onClick={() => props.delete(item)}>Delete</button>
      </li>);
    )}

Here's a working version of your code sandbox

first make a delete function pass it a ind parameter and then use filter method on your array in which you saved the added values like

function delete(ind){
       return array.filter((i)=>{
            return i!==ind;
   })
}

by doing this elements without the key which you tried to delete will not be returned and other elements will be returned.

Related