2

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

2 Answers 2

2

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})
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.