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

128
Visualizações
Adding user input with state array in React

I have an existing array of data in a separate file that I am adding to with user input. The user input I am taking is 3 favorite movies. I am able to receive and push the rest of the data to an existing file. I am not sure if the state array is throwing me off but I am not able to add 3 strings into the array.

My state is as follows:

this.state = {
  isActive: false,
  id: 25,
  name: { first: "", last: "" },
  city: "",
  country: "",
  employer: "",
  title: "",
  favoriteMovies: ['', '', '']
};

I am setting the state for user input as follows:

 handleFavoriteMoviesChange = (e) => {
    this.setState({ favoriteMovies: [...this.state.favoriteMovies, e.target.value]})
 };

These are my 3 input fields:

    <input
      placeholder="favorite movies"
      value={this.state.favoriteMovies[0]}
      onChange={this.handleFavoriteMoviesChange}
    />
    <input
      placeholder="favorite movies"
      value={this.state.favoriteMovies[1]}
      onChange={this.handleFavoriteMoviesChange}
    />
    <input
      placeholder="favorite movies"
      value={this.state.favoriteMovies[2]}
      onChange={this.handleFavoriteMoviesChange}
    />
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you want to set the value of the favoriteMovies on its particular index then you can setState as below: CODESANDBOX DEMO

  handleFavoriteMoviesChange = (e, index) => {
    this.setState({
      favoriteMovies: this.state.favoriteMovies.map((movie, i) => {
        if (i === index) return e.target.value;
        return movie;
      })
    });
  };

and call handleFavoriteMoviesChange as:

<input
  placeholder="favorite movies"
  value={this.state.favoriteMovies[0]}
  onChange={(e) => this.handleFavoriteMoviesChange(e, 0)}
/>
<input
  placeholder="favorite movies"
  value={this.state.favoriteMovies[1]}
  onChange={(e) => this.handleFavoriteMoviesChange(e, 1)}
/>
<input
  placeholder="favorite movies"
  value={this.state.favoriteMovies[2]}
  onChange={(e) => this.handleFavoriteMoviesChange(e, 2)}
/>
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