Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

135
Views
Why does it not push the element into the array state "tasks"?

I'm trying to create a todo app in React. I'm currently trying to print the input when i press the + button, but it is not working. Can anyone help to check my syntax!

import React from 'react';
import './App.css';

class App extends React.Component {
  constructor(){
    super();
    this.state = {
      value: '',
      tasks: []
    };

    this.handleChange = this.handleChange.bind(this)
    this.addItem = this.addItem.bind(this)
  }

  handleChange(event) {
      this.setState({
        value: event.target.value
      })
  }

  addItem(){
      this.state.tasks.push(this.state.value)
  }

  render(){

    return(
      <div>
              <input type="text" value={this.state.value} onChange={this.handleChange}></input>
              <button onClick={this.addItem}>+</button>
              <button>-</button>
              <h1>{this.state.tasks}</h1>  
      </div>
    )
  }
}


export default App;

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

To change the state you should use this.setState. Refer to https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly. Reading React documentation might save you a lot of time overall.

about 4 years ago · Juan Pablo Isaza Report

0

You need to setState task

addItem() {
    const newTask = [this.state.value, ...this.state.tasks];
    this.setState({ tasks: newTask });
    this.setState({ value: "" });
  }

enter image description here

about 4 years ago · Juan Pablo Isaza Report

0

Modifying state directly is not the correct way!

instead use setState:

this.setState({
  tasks: this.state.tasks.concat(this.state.value)
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!