Home > database >  MUI Autocomplete – start filtering from 3 character
MUI Autocomplete – start filtering from 3 character

Time:10-27

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?

CodePudding user response:

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.

  • Related