Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
Todo won't toggle as completed/not completed in React app

I've got the following handleChange function in my App component that is supposed to toggle todo items as completed or not completed. As a side note, I intend to update the code to use React Hooks in the future.

import React from "react"
import TodoItem from "./TodoItem"
import todosData from "./todosData"
import './styles.css'

class App extends React.Component {
    constructor() {
        super()
        this.state = {
            todos: todosData
        }
        this.handleChange = this.handleChange.bind(this)
    }
    
    handleChange(id) {
        this.setState(prevState => {
            const updatedTodos = prevState.todos.map(todo => {
                if (todo.id === id) {
                    todo.completed = !todo.completed;
                }
                return todo
            })
            return {
                todos: updatedTodos
            }
        })
    }
    
    render() {
        const todoItems = this.state.todos.map(item => <TodoItem key={item.id} item={item} handleChange={this.handleChange}/>)
        
        return (
            <div className="todo-list">
                {todoItems}
            </div>
        )    
    }
}

The following line as it currently is doesn't update the completed status of the todo.

if (todo.id === id) {
                    todo.completed = !todo.completed;
                }

However if I change it to something like the following, then it updates!?

if (todo.id === id) {
                    todo.completed = false;
                }

However, I want it to toggle the completed status whether it's true or false and I can't see why the example I've used won't work as googling the problem seems to suggest it should.

Does anybody know why my code doesn't work currently? Any help is appreciated.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!