user321
user321

Reputation: 175

ReactJS: add a new input field on an option select

I'm using react-select with isMulti. I am trying to add a new input field when user selects an option from dropdown. I have somehow achieved it. I am facing a problem, let's say if I select 1st option from dropdown then it adds the input field for that particular option and when I try to select second option then 2 new input fields are added (1 for the previously selected option and the other for current selected option). In this way, I get 3 new input fields but I should be getting 2 input fields because I have selected only 2 options. Below is my code.

 onChange = (e) => {
   if(e){
     e.map((item) => {
     this.state.selectValue.push(item.value);  
    })
  }
}
this.state.selectValue.map((item) => {
  return(
    <div className="row m-3">
      <label className="col-md-4">{item}</label>
      <div className="col-md-7">
        <input type="text" name={item} className="form-control"  />
      </div>
    </div>
   )                                                    
})


 <Select
    isMulti
    options={this.state.options}
    onChange = {(e) => this.onChange(e)}
    classNamePrefix="select"
 /> 

Note: I am storing the option's value as a "name" of input field to keep track of the quantity.

In the screenshot when I selected first then an input field with "first" label was displayed but when I selected "second" then 2 input fields showed up as highlighed in the image.

enter image description here

Upvotes: 2

Views: 2460

Answers (2)

Pierre Mvogo
Pierre Mvogo

Reputation: 1

Updating state within a loop causes sideffects with the way the component re-renders. Try using a temporary array in your handler and then override state after your map function.

Upvotes: 0

Hyetigran
Hyetigran

Reputation: 1215

Updating state within a loop causes sideffects with the way the component re-renders. Try using a temporary array in your handler and then override state after your map function.

 onChange = (e) => {
   if(e){
     let arr = []
     e.map((item) => {
     arr.push(item.value);  
    })
    this.setState({selectValue: arr})
  }
}

Upvotes: 2

Related Questions