0

I have been working on a todo list in react, and ran into a problem I've been having trouble figuring out. I managed to get the todo list to dynamically update my array state, but having a little problem with displaying it. Here is the code: (https://codesandbox.io/s/friendly-curran-fldtg?fontsize=14). At the top I give a brief explanation of what everything does. The problem area is at the bottom, this line of code:

const DisplayTasks = () => {
  const { tasksarray } = this.state;
  return (
    <ol>
      {tasksarray.map(eachTask => (
        <li>{eachTask}</li>
      ))}
    </ol>
  );
};

I'm able to get the app working the way I want it by deleting the DisplayTask component and putting the ol code in render() like so:

  render() {                                                      
  const { tasksarray } = this.state;
  return (
    <div>
      <GetTask task={this.inputTask} />
      <ol>
        {tasksarray.map(eachTask => (
          <li>{eachTask}</li>
        ))}
      </ol>
    </div>
    );
  }
}

But I'm wondering why I get TypeError Cannot read property 'state' of undefined when I try to do it as a component, and if there's a way to make it work as a component rather than directly in render()?

1 Answer 1

4

You can't access this.state in Functional Component.

In react, the parent component can pass data to the child using the props like below

 const DisplayTasks = ({tasks}) => {
    return (
     <ol>
      {tasks.map((task, index) => <li key={index}>{task}</li>)}
     </ol>
    );
 };


 render() {                                                      
   return (
     <div>
       <GetTask task={this.inputTask} />
       <DisplayTasks tasks={this.state.tasksarray} />
     </div>
   );
 }
Sign up to request clarification or add additional context in comments.

1 Comment

Makes sense. Thanks for the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.