I've imported the Autocomplete component from MaterialUI in my React project and using it as a multiple select with checkboxes: https://material-ui.com/components/autocomplete/#checkboxes
I noticed that when I type into the input to filter the list and then select a value, the filter inserted by the user resets. I want to avoid this and continue to multi-select with the filter instead of reinsert it every time. I didn't find any props in the component API to solve this.
Any suggestion?
That's my component code:
const VirtualAutocomplete = (props) => {
const classes = useStyles();
const textClasses = textStyles();
return (
<Autocomplete
id={props.id}
style={{ width: 'auto' }}
value={props.value}
limitTags={4}
noOptionsText="No records found."
classes={classes}
disableCloseOnSelect
ListboxComponent={ListboxComponent}
renderGroup={renderGroup}
onChange={props.onChange}
options={props.options}
filterOptions={startsWith}
multiple={props.multiple}
renderInput={(params) =>
<ThemeProvider theme={theme}>
<TextField {...params}
variant='outlined'
classes={{ root: textClasses.formControlRoot }}
InputLabelProps={{ classes: { root: textClasses.labelRoot } }}
label={props.label}
/>
</ThemeProvider>
}
renderOption={(option, { selected }) => (
<Fragment>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option}
</Fragment>
)}
/>
);
}
Create a state that holds input value. Then on TextField onChange pass the function to change this state. Then on Autocomplete pass the props inputValue with that state content. You can also use disableCloseOnSelect props to Autocomplete so options box doesnt close on option selected.
Take a look at their docs about those props https://material-ui.com/pt/api/autocomplete/
Here is a example using their demo: https://codesandbox.io/s/material-demo-forked-pdh81?file=/demo.js:746-766
export const AutocompleteNonClearnableOnSelect = observer((props: AutocompleteProps<any, any, any, any>) => {
const [value, setValue] = useState("");
return <Autocomplete {...props}
onInputChange={(_, value, reason) => reason !== 'reset' && setValue(value)}
inputValue={value}/>;
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With