0

I'm a beginner in react.js. I have some problems with the function handleChange in the middle of app.js

Here are my questions:

  1. When to use return in an arrow function.I know there's a return in function handleChange, but I have seen some of the arrow function with curly brackets that doesn't have a return in it.

  2. I'm not really understand the first return todo do? I mean it only return one piece of the changed data and assign to const updateTodos, but updatesTodos seems to be the whole data.

Please help :(

app.js:

import React from "react"
import TodoItem from "./TodoItem"
import todosData from "./todosData"

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>
        )    
    }
}

export default App

todosData.js:

const todosData = [
    {
        id: 1,
        text: "Take out the trash",
        completed: true
    },
    {
        id: 2,
        text: "Grocery shopping",
        completed: false
    },
    {
        id: 3,
        text: "Mop the floor",
        completed: false
    },
    
]

export default todosData
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Yan Skywalker
  • 119
  • 1
  • 10
  • 1
    The `handleChange` implementation there is broken, because you're mutating the existing state. If you took that from a tutorial, I'd highly recommend ditching that tutorial and finding one from a different site – CertainPerformance Feb 18 '21 at 15:53
  • 1
    The `return todo` means that the item returned from the `.map` callback is the same element being iterated over. `.map((item) => { /* ... */ return item; })` makes a shallow copy of the array being mapped. – CertainPerformance Feb 18 '21 at 15:54

0 Answers0