State Value not changing in react drop down

I have a drop down menu in react where the state changes if I select the second item in the menu but if a change the menu back to the first item the state does not update unless i choose the second item twice. I have tried placing the code in a useEffect with colorDrop in the dependency array but it still does not work correctly. Here is my code if anyone has any idea how to fix this issue.


currentArray = ["blue", "grey"]
 const [colorDrop, setColorDrop] = useState(currentArray[0])


 function Dropdown() {

        return (
            <div>
                <form>
                    <label>Color</label>
                    <select required onChange={(e) => setColorDrop(e.target.value)}>
                        {currentArray.map((item, iter) => {
                           
                           
                            return (
                                <option key={iter}>{item}</option>

                            )
                        })}
                    </select>

                </form>
            </div>
        )

    }

this “select” element is not a “controlled” component, make use of “value” attribute with help of a “useState” hook to keep track of “updated” value after any changes occur

happy coding :slight_smile:

I changed this to a separate function and if I console log e to get the event object the useChange does not fire if I choose grey then choose blue again. It seems like the above code is using the useState hook to set it to e.target value already.

I set a default option above the map of the array and now it works correctly.

 function Dropdown() {

        return (
            <div>
                <form>
                    <label>Color</label>
                    <select required  onChange={(e) => changeColor(e)}>
                    <option default value="">---</option>
                        {currentProduct.colorArray.map((item, iter) => {
                          
                            
                            return (
                                <option id={iter} key={iter}>{item.color}</option>

                            )
                        })}
                    </select>

                </form>
            </div>
        )

    }

That wasnt quite working i had to pass the state back into the value of select to get the dropdown to update correctly. In the past that wasnt necessary

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.