Home > Software engineering >  Adding user input with state array in React
Adding user input with state array in React

Time:10-05

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}
    />

CodePudding user response:

You are setting the state to just include favoriteMovies. The correct way would be:

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

CodePudding user response:

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)}
/>
  • Related