Panayiotis Spanos
Panayiotis Spanos

Reputation: 155

Functional component to class component Error: Cannot read property 'id' of undefined

I'm working on a small project and am in the process of translating a functional component to a class based component so that my component can manage its state. In translating the component over, I've run into an error:

TypeError:Cannot read property 'id' of undefined

This component worked as a functional component so I'm not sure why I'm receiving this error now. Can anyone answer why in translating from a functional component to a class based one that I'm receiving this error? Is this something to do with scope at all? Do I just have some syntax wrong? I've been banging my head against this for a while and just can't understand why it cannot read the property of 'id' which is in now in the return of the render portion of my component.

Component code:

  import React, {Component} from "react";
import "./OpenTasksComponent.css"



class openTasks extends Component{
  constructor(){
      super();

    this.handleClick = this.handleClick.bind(this);
  }

     handleClick(){
        let x = document.body.nodeName;
        console.log(x);
    }
    
    render(){

        return (
    
            <div className="tasks" value = {this.task.id}>
                <h1 onClick={this.handleClick}>{this.task.clientName}</h1>
                <div className="accordion-item accordion-item-open">
                    <h2>{this.task.matter}</h2>
                    <p>{this.task.matterStatus}</p>
                </div>
            </div>
        )

    }
    
    
}

export default openTasks

App code:

import './App.css';
import Task from './components/open-tasks-component/open-tasks-component';
import tasksData from './components/open-tasks-component/tasks-data';
import Header from './Header';

function App() {
  const Tasks = tasksData.map(task=> <Task key={task.id} task ={task}/>)
  return (
    <div className="App">
        <Header />
    
        {Tasks}
    </div>
  );
}

export default App;

Upvotes: 1

Views: 190

Answers (2)

First Arachne
First Arachne

Reputation: 829

Functional components can also manage states. You can use useState.

const [state, setState] = useState(null);

Upvotes: 0

Rachid Amri
Rachid Amri

Reputation: 36

In App you passed a prop down, but you tried to read it in the child class component using this.task.id it should be this.props.task.id

Upvotes: 2

Related Questions