Dropdown: call onAddItem after onChange
See original GitHub issueSteps
(Using the testcase)
- Use options with distinct
text
andvalue
properties; - In a Dropdown with
allowAdditions
set, type a new entry and confirm addition;
Expected Result
A way to set a custom value to the newly added item is provided before it is auto-selected.
Actual Result
The newly added item has both its text
and value
properties set to the input text and is then selected based on that string.
This is caused by the item insertion logic in getMenuOptions that sets both the text
and value
properties of new items to the user-inserted text when the user confirms the entry. onAddItem
is then called with the new value (which is fine), immediately followed by setValue
, setSelectedIndex
and handleChange
, which attempt to select the item using the same value.
This behavior gives no opportunity to set an appropriate value property (a unique ID, for instance) to the newly inserted item before it is auto-selected. In the testcase, this is attempted in the onAddItem
handler, but setting the value property there means the setValue
, setSelectedIndex
and handleChange
calls fail as they use the old value (the user-inserted text). There is then no elegant way to select the newly added item.
Version
0.73.1
Testcase
Issue Analytics
- State:
- Created 6 years ago
- Reactions:1
- Comments:5 (3 by maintainers)
Top GitHub Comments
I want to include this in next release, so picking up
Hey layershifter! Thanks for looking at this.
It already is a controlled component. The
currentValue
state is used to store the value.The modified pen allows selection of the newly added value because there are now two states that hold the value (
state.currentValue
andstate.value
), but then other items can no longer be selected asstate.value
has priority (the newly added item remains selected until another item is added).If we use the same state to hold value in both the
onAddItem
andonChange
handlers, the state change inonAddItem
is ignored as the code ingetMenuOptions
immediately callshandleChange
(which callsonChange
), changing the state to the initial value (the user-inserted text). (codepen)It’s possible to work around this by storing the newly added value in a class property (in the
onAddItem
handler), then using that when changing the value state in theonChange
handler, although that’s not the cleanest of ways. (codepen)My guess is that a new function prop that allows customizing the value for new items would resolve this, but I’d like to hear your thoughts first.