Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

194
Visualizações
React toDoApp removing a task functionality not working

I am a new to React and trying to make a toDoApp. I'm trying to create an onClick event to remove an element from the tasks state. But it does not seem to work. And can I also ask how to implement id keys so that I can remove the desired task that I want?

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)
    this.removeItem = this.removeItem(this)
  }

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

  addItem(){
    if(this.state.value === ''){
      alert('Enter a task!')
    } else {
      const newTask = [...this.state.tasks, this.state.value]
      this.setState({
      tasks: newTask,
      value: ''
      })
    }
    }

  removeItem(){
    this.state.tasks.pop()
    this.setState({
      tasks: this.state.tasks,
    })

  }

  render(){

    const itemList = this.state.tasks.map((num) => 
              <li>{num}</li>
            );

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


      </div>
    )
  }
}


export default App;

strong text

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

pop() removes the last element, but React will not rerender the component as setState is called with the same array. You can create a new array and use it for updating the state.

removeItem() {
    this.state.tasks.pop()
    this.setState({
      tasks: [...this.state.tasks],
    })
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda