Home > Software design >  Question on adding a input value to an array using setState
Question on adding a input value to an array using setState

Time:11-22

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?

CodePudding user response:

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

CodePudding user response:

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"/>
  • Related