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

180
Visualizações
Question on adding a input value to an array using setState

I'm trying to use setState to update a state array in React using a basic HTML input. The state I'm trying to update looks like:

 "businessName": "",
  "grossAnnualSales": 0,
  "contactEmail": "",
  "numEmployees": 0,
  "annualPayroll": 0,
  "locations": [{"zip": ""}],
  "industryId": "",

I need to add a zip code inputted by the user in a React component to this object in the array.

So far I've tried this and it's not working, it just updates to a string and not an array:

updateZip(){
return e => this.setState({"locations": [{"zip": e.currentTarget.value}]}) 

}

The React component:

<input onChange={this.updateZip()} type="text" className="zip-input"/>

How can I update the state succesfully?

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

0

use e.target.value and pass onChange={this.updateZip}

   class App extends Component {
  state = {
    locations: [{ zip: "" }]
  };
  updateZip = (e) => {
    this.setState({ locations: [{ zip: e.target.value }] });
  };

  render() {
    return (
      <div>
        <input onChange={this.updateZip} type="text" className="zip-input" />
        <p>{this.state.locations[0].zip}</p>
      </div>
    );
  }
}
export default App;

CodeSandBox

about 4 years ago · Juan Pablo Isaza Relatório

0

Try replacing your updateZip function with an arrow function.

updateZip = (e) => {
    return e => this.setState({"locations": [{"zip": e.currentTarget.value}]}) }

Also

<input onChange={(e) => this.updateZip(e)} type="text" className="zip-input"/>
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