Search code examples
javascriptreactjsreact-props

TypeError: this.props.deleteItem is not a function


I have 2 components one for the list of todo items and the other for the Todo form In todo form component I want to pass deleteItem function from TodoForm component to the todo list item component, However I always get that error TypeError: this.props.deleteItem is not a function

class Todo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      todoList: [],
      newItem: "",
      newDescription: "",
      chkbox: false,
    };
  }
  deleteItem = (id) => {
    const todoList = this.state.todoList.filter(function (item) {
      return item.id !== id;
    });
    this.setState({ todoList });
  };
 render() {
    return (
      <div className="Todo">
        <form id="to-do-form" onSubmit={this.addItem}>
          .....
          <button type="submit">Add</button>
        </form>
        <ListItems
          items={this.state.todoList}
          deleteItem={this.state.deleteItem}
        ></ListItems>
      </div>
    );
  }
}

export default Todo;

In todo list items component I use this.props.deleteItem

class ListItems extends Component {
  render() {
    const list_items = this.props.items;
    return (
      <div>
        <ul>
          {list_items.map((item) => {
            return (
              <li className="list-item" key={item.id}>
                ....
                <button
                  onClick={() => {
                    if (
                      window.confirm(
                        "Are you sure you wish to delete this item?"
                      )
                    )
                      this.props.deleteItem(item.id);
                  }}
                >
                  <i className="material-icons">x</i>
                </button>
              </li>
            );
          })}
        </ul>
      </div>
    );
  }
}

export default ListItems;

Solution

  • deleteItem is not a state. Just update props pass to ListItems like this:

        <ListItems
          items={this.state.todoList}
          deleteItem={this.deleteItem}
        ></ListItems>