-1
import React from "react"
import Header from "./Header"
import ToDoItem from "./ToDoItem"
import toDoData from "./toDoData"

class App extends React.Component{
    constructor(props){
        super(props) 
        this.handleChange=this.handleChange.bind(this)
    }

    handleChange(id){
        console.log("Id value : ",id)
    }

    render(){
        const toDoTasks = toDoData.map(function (toDos){
            return <ToDoItem 
                        key={toDos.id}
                        handleChange={this.handleChange} // Line 26
                    />
        })

        return(
                <div className="rootComponent">
                    <Header />
                    {toDoTasks}
                </div>
        )
    }
}

export default App

Error

TypeError: this is undefined

render/toDoTasks<

src/components/App.js:26

Here in my code I'm trying to attach my handleChange function to my <ToDoItem /> component.But here I'm unable call handleChange function.If I define the function inside the constructor then I can call the function but I dont want my function inside the constructor.How can I do this.

Vasu Ch
  • 185
  • 2
  • 12

1 Answers1

2

The issue is here

 const toDoTasks = toDoData.map(function (toDos){
            return <ToDoItem 
                        key={toDos.id}
                        handleChange={this.handleChange} // Line 26
                    />
        })

function (toDos) creates a separate scope and this no longer refers to your class instance.

Changing that to

 const toDoTasks = toDoData.map(toDos => <ToDoItem key={toDos.id} handleChange={this.handleChange}/>);

will work as expected, as arrow functions retain the parent scope and don't create their own.

bamtheboozle
  • 5,847
  • 2
  • 17
  • 31