Codesandbox: https://codesandbox.io/s/magical-black-vp1r0?file=/src/dropdown-selector.js
I'm trying to build a very specific component and I'm not sure if its even possible or not. Please let me know.
Requirements:
- SelectBox must be a CONTROLLED INPUT
- DropdownSelector component can be consumed in any way possible (aka do not change App.js)
- when clicking one of the options from the dropdown options, the value replaces the inputfield value
Reasons
- I'm using react-intl and it only works for controlled inputs (translates instantly if value is controlled)
- This component is a part of a monorepo, meaning the UI component should be versatile enough to be consumed in any way possible
- The purpose of this component is a dropdown selector, meaning the user can type in a word and autocomplete options will dropdown for the user to click and "complete" their search
The dilemma is, if I want the component to be controlled, I must only use setVal
method to change the state/value. For example, val
can only be changed through setVal
for a typical react input component like below:
const [val, setVal] = useState();
<input value={val} onChange={e => setVal(e.target.value)} />
However, in order for the dropdown option to replace the value of the input component, it must change the value state. But controlled components only have 1 way to change state and that's setVal
in this case AND I can't change the way onChange consumes setVal because this is a UI component that should be able to be used in any versatile way.
So my question is: even though I'm sounding very hypocritical, is there a way to change that input component's value without using setVal
?
Specific example in codesandbox above. Specific issue is in line 128 of DropdownSelector.js. Thank you very much in advance.