I'm building a "todo" app for practicing & learning React basics. I have an array of objects from a file called TodosStores.js which I passed down as props to the TodoList component like so:
import TodoList from './components/TodoList';
import TodosStores from './stores/TodosStore';
function App() {
return (
<div className="App">
<TodoList todos={TodosStores} />
</div>
);
}
export default App;
Now, I'm trying trying to toggle the property value of the current todo.completed to true & false so I can remove/add the todo-item-completed class. However, I'm getting this error: TypeError: Cannot create property 'completed' on boolean 'true'. I am seeking some explanation of what I'm doing wrong here. I come from Vue background so probably there's another way of changing the state in React.
This is my component's code snippet:
import React, { Component } from 'react';
import './TodoListStyles.css'
class TodoList extends Component {
constructor(props){
super(props);
this.state = { todos: this.props.todos }
this.handleChange = this.handleChange.bind(this);
}
handleChange(item) {
return item.completed = !item.completed
}
render() {
return (
<ul className='todo-list'>
{
this.props.todos.map(
todo =>
<React.Fragment key={todo.id}>
<li className={`todo-item ${todo.completed ? 'todo-item-completed' : ''}`}>{ todo.title }</li>
<input type='checkbox' onChange={this.handleChange(todo.completed)} checked={todo.completed} />
</React.Fragment>
)
}
</ul>
)
}
}
export default TodoList;
PS: I'm using React Class Components because I want to contribute to an open-source project which uses class components. I might try refactoring later to hooks.
The reason you are getting error TypeError: Cannot create property 'completed' on boolean 'true' is because you are passing boolean value to handleChange in onChange={this.handleChange(todo.completed)} and in the function you are creating/mutating item.completed.
It can not create property completed on true or false basically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With