Reputation: 29
I keep getting the following error:
TypeError: this.props.onDelete is not a function
I have .bind(this) on the functions in render(), but this error seems to keep occurring and I don't know why. Here is the relevant code:
App.js
import React, {Component} from 'react';
import Todos from './Components/Todos';
class App extends Component {
deleteTodo(id) {
let todos = this.state.todos;
for (let i = 0; i < todos.length; i++) {
if (todos[i].id === id) {
todos.splice(i, 1);
break;
}
}
this.state.todos = todos;
}
render() {
return (<div className="App">
<h1>React Todo App</h1>
<AddTodo/>
<Todos todos={this.state.todos} onDelete={this.deleteTodo.bind(this)}/>
</div>);
}
}
export default App;
Todos.js
import React, {Component} from 'react';
import Todo from './Todo';
class Todos extends Component {
delete(id) {
this.props.onDelete(id);
}
render() {
let todoItems = '';
if (this.props.todos) {
todoItems = this.props.todos.map(todo => {
return (<Todo id={todo.id} name={todo.name})></Todo>)
});
}
return (<ul class="todos" onDelete={this.props.onDelete.bind(this)}>{todoItems}</ul>);
}
}
export default Todos;
Todo.js
import React, {Component} from 'react';
class Todo extends Component {
delete(id) {
this.props.onDelete(id);
}
render() {
return (<li class="todo" id={this.props.id}>{this.props.name}
<a onClick={this.delete.bind(this, this.props.id)} class='remove-button' href='#'>X</a>
</li>)
}
}
export default Todo;
The error seems to be occurring at Todo.js in the following code snippet:
delete(id) {
this.props.onDelete(id) // Error
}
Edit: Added more code for context
Upvotes: 1
Views: 9350
Reputation: 112787
By writing this.delete(this.props.id).bind(this)
you are calling your this.delete
function instead of giving onClick
a function reference.
You could write it like this:
onClick={this.delete.bind(this, this.props.id)}
Or use an arrow function:
onClick={() => this.delete(this.props.id)}
Upvotes: 2