Home > Back-end >  React: Can't add a new task to my tasks's array
React: Can't add a new task to my tasks's array

Time:01-11

I'm new to React and I'm trying create a To Do List project. I'm trying to add a new task to my tasks's array via input, but when I press Enter nothing is added to screen. Can someone help?

App.js

import React, { Component } from "react";
import Tasks from "./Components/tasks";

class App extends Component {

    constructor(props) {
      super(props);

      this.state = {
          newTask: '',
          tasks: [
              { id: 1, text: "study" },
              { id: 2, text: "read" },
              { id: 3, text: "gym" },
          ]
      };
    }

    handleSubmit(e) {
      e.preventDefault();
      const tasks = [...this.state.tasks];
      tasks.push({id: 4, text: this.state.newTask});
      this.setState({ tasks: tasks });
    }

    handleChange= (e) => {
      this.setState({newTask: e.target.value});
    }

    render() {
        return (
            <div className="App">
                <h1>To Do List</h1>

                <form onSubmit={this.handleSubmit}>
                  <input type="text" placeholder="Enter task" value={this.state.newTask} onChange={this.handleChange}/>
                </form>

                <Tasks tasks={this.state.tasks} />
            </div>
        );
    }
}

export default App;

Adicionaly I'm getting this error on the console: error

CodePudding user response:

you need to bind your function to the class

simple solution is to use arrow function syntax

   handleSubmit = (e) =>  {

instead of

handleSubmit(e) {

there are other ways to do it as well..

you can read this article to understand more https://www.freecodecamp.org/news/this-is-why-we-need-to-bind-event-handlers-in-class-components-in-react-f7ea1a6f93eb/

  • Related