I've created a to do list with React. I want to be able to mark tasks completed simply by clicking on them. I also want to be able to clear task that have been completed by clicking a button. These two functions are not working correctly with the code I have set up. When I click on an individual todo item to mark it complete, every single to do item on the list gets marked complete and thus, appears with a 'line-through.' When I then click the designated button to clear completed tasks, absolutely nothing happens. Can someone help me resolve these two issues?
code from App component:
class App extends React.Component {
constructor() {
super();
this.state = {
todos: [
{
task: "learn how to fly drone",
id: Date.now(),
completed: false
},
{
task: "learn React class components",
id: Date.now(),
completed: false
},
{
task: "practice editing videos",
id: Date.now(),
completed: false
},
{
task: "read Ten Years A Nomad",
id: Date.now(),
completed: false
}
],
todo: ''
}
}
inputChangeHandler = event => {
this.setState({[event.target.name]: event.target.value})
}
addTask = event => {
event.preventDefault();
let newTask = {
task: this.state.todo,
id: Date.now(),
completed: false
};
this.setState({
todos: [...this.state.todos, newTask],
todo: ''
})
}
toggleComplete = itemId => {
const todos = this.state.todos.map(todo => {
if (todo.id === itemId) {
todo.completed = !todo.completed
}
return todo
});
this.setState({todos, todo: ''})
}
clearCompleted = e => {
e.preventDefault();
return this.state.todos.filter(item => !item.completed)
}
render() {
return (
<div className="App">
<h2>Welcome to your Todo App!</h2>
<TodoList
todos={this.state.todos}
toggleComplete={this.toggleComplete} />
<TodoForm todos={this.state.todos} value={this.state.todo} inputChangeHandler={this.inputChangeHandler} addTask={this.addTask} clearCompleted={this.clearCompleted}/>
</div>
);
}
}
export default App;
TodoList:
const TodoList = props => {
return (
<div>
{props.todos.map((todo, id) => (
<Todo
todo={todo}
key={id}
toggleComplete={props.toggleComplete} />
))}
</div>
)
}
export default TodoList;
Todo:
const Todo = props => {
return (
<div
key={props.todo.id}
onClick={() => {
props.toggleComplete(props.todo.id)
}}>
<p
style={{textDecoration: props.todo.completed ? 'line-through' : 'none'}}>
{props.todo.task}
</p>
</div>
)
}
export default Todo;
TodoForm:
const TodoForm = props => {
return (
<form>
<input
name="todo"
value={props.value}
type="text"
onChange={props.inputChangeHandler}
placeholder="Enter new task" />
<button onClick={props.addTask}>Add Todo</button>
<button onClick={props.clearCompleted}>Clear Completed</button>
</form>
)
}
export default TodoForm;