0

I'm using MUI 5 Autocomplete component with a long list for the options property Because I got some delay between the time the user clicked on the select and the time the list was open I'm trying to add the "react-window" VariableSizeList to the options list for better performance.

It's working but when the list got a long text item(more than 1 row) the CSS looks bad:

enter image description here

the Autocomplete JSX:

  return (
     <Autocomplete
      size="small"
      disableListWrap
      options={[{displayName: "option1"},
        {displayName: "option2 more than one row - long text css looks bad"},
        {displayName: "option3 more than one row - long text css looks bad"},
        {displayName: "option4 more than one row - long text css looks bad"},
        {displayName: "option5 more than one row - long text css looks bad"},
        {displayName: "option6 more than one row - long text css looks bad"},
        {displayName: "option7"},
        {displayName: "option6"},
      ]}
      ListboxComponent={ListBoxComponent}
      onChange={onSelectChange.bind(null, fieldName)}
      getOptionLabel={(option) => option.displayName || ""}
      value={value}
      isOptionEqualToValue={(selected, value) => selected.displayName === value.displayName}
      renderOption={(props, option) => [props, option]}
      renderInput={(params) => (
        <TextField {...params} variant="outlined" placeholder={"Select"} />
      )}
    />
  )

and the ListBoxComponent:

  const ListBoxComponent = React.forwardRef((props: any, ref: any) => {
    const { children, ...other } = props
    const itemData: any = []
    children.forEach((item: any) => {
      itemData.push(item)
      itemData.push(...(item.children || []))
    })

    const itemSize: number = 45

    return (
      <div ref={ref} {...other}>
        <VariableSizeList height={300} itemData={itemData} itemCount={itemData.length} itemSize={() => itemSize}>
          {renderRow}
        </VariableSizeList>
      </div>
    )
  })

And the render row JSX:

const renderRow = ({ index, data, style }: any): JSX.Element => {
    const dataSet = data[index]
    const displayOption: string = dataSet[1].displayName

    return (
      <li style={style} {...dataSet[0]}>
          <Typography>
            {displayOption}
          </Typography>
      </li>
    )
  }

My guess is it's because of the itemSize value I have to set in the ListBoxComponent but I couldn't find a way how to set it right for multirow items.

Ar26
  • 949
  • 1
  • 12
  • 29

0 Answers0