Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MUI Autocomplete – start filtering from 3 character

I have such Autcomplete mui component which make a filter over a list of checkboxes. Popup with options should always stay opened. What I need to do is to trigger filtering only when user input is more than 3 characters.

<Autocomplete
    open
    multiple
    disableCloseOnSelect
    options={permissions as Permission[]}
    getOptionLabel={(option) => option.name}
    disablePortal
    renderTags={() => <div>{`${values.permissions?.length} Selected`}</div>}
    id="combo-box-demo"
    renderInput={(params) => <TextField {...params} label="Permissions" name="search" />}
    ListboxProps={{ style: { maxHeight: '240px' } }}
    renderOption={({ name }) => (
        <Field
            style={{ height: '30px' }}
            as={FormControlLabel}
            name="permissions"
            value={name}
            label={name}
            control={<Checkbox color={'primary'} checked={values.permissions?.includes(name)} />}
        />
    )}
/>

This sounds like pretty simple task but after digging into documentation and googling I haven't found any solution for my particular case (input is uncontrolled and popup should always be in place). Could anyone help with that?

like image 891
Kiril Avatar asked Oct 31 '25 07:10

Kiril


1 Answers

You should use filterOptions with your custom logic for this.

 filterOptions={(options, state) => {
        console.log(options);
        if (state.inputValue.length > 2) {
          return options.filter((item) =>
            String(item.label).toLowerCase().includes(state.inputValue.toLowerCase())
          );
        }
        return options;
      }}

See the working here

You can use any filter logic, I am just checking (case insensitive search) for the input string anywhere in the label.

like image 83
kiranvj Avatar answered Nov 02 '25 22:11

kiranvj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!