Skip to content

Commit 9f48d93

Browse files
authored
feat(autocomplete): new parameter to allow custom user input (#44)
1 parent d937d6a commit 9f48d93

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

demo/FormExamples.jsx

+9
Original file line numberDiff line numberDiff line change
@@ -176,6 +176,15 @@ export function FormExamples() {
176176
required={() => false}
177177
/>
178178
</div>
179+
<div className="col">
180+
<FormGroupAutocomplete
181+
name="autocompleteField4"
182+
label="Autocomplete that allows custom user input"
183+
options={['1234', '2345', '3456']}
184+
placeholder="Type some numbers"
185+
allowUnlistedValue={true}
186+
/>
187+
</div>
179188
</div>
180189

181190
<div className="row">

src/forms/FormAutocomplete.jsx

+16-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ export function FormAutocomplete({
2121
filter,
2222
disabled: _disabled,
2323
afterChange,
24+
allowUnlistedValue,
2425
}) {
2526
const { getValue, setValue: _setValue, register, isValid, getFormSubmitedAttempted, getFormData } = useFormControl(
2627
name
@@ -98,6 +99,8 @@ export function FormAutocomplete({
9899
setValue('');
99100
setSelectedItem(null);
100101
updateSearchInputValidation();
102+
} else if (isEmptyLike(selectedItem) && !isEmptyLike(searchValue) && allowUnlistedValue) {
103+
onSelectItem({ value: searchValue, label: searchValue });
101104
}
102105

103106
if (ignoreBlur) {
@@ -106,7 +109,17 @@ export function FormAutocomplete({
106109
close();
107110
setFocus(false);
108111
}
109-
}, [close, ignoreBlur, searchValue, setValue, updateSearchInputValidation, value]);
112+
}, [
113+
close,
114+
ignoreBlur,
115+
searchValue,
116+
setValue,
117+
updateSearchInputValidation,
118+
value,
119+
onSelectItem,
120+
allowUnlistedValue,
121+
selectedItem,
122+
]);
110123

111124
const enableSearchInput = useCallback(() => {
112125
if (disabled) {
@@ -201,6 +214,7 @@ FormAutocomplete.defaultProps = {
201214

202215
FormAutocomplete.propTypes = {
203216
afterChange: PropTypes.func,
217+
allowUnlistedValue: PropTypes.bool,
204218
disabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
205219
filter: PropTypes.func,
206220
id: PropTypes.string,
@@ -227,6 +241,7 @@ export function FormGroupAutocomplete(props) {
227241

228242
FormGroupAutocomplete.propTypes = {
229243
afterChange: PropTypes.func,
244+
allowUnlistedValue: PropTypes.bool,
230245
disabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
231246
filter: PropTypes.func,
232247
help: PropTypes.node,

0 commit comments

Comments
 (0)