I have Autocomplete to select multiple options from React MUI. When out of focus, I want it to show only that amount of tags, that fits into one row. I can use limitTags={3}, to limit the number of tags.
But There are two issues:
- If the input is shorter(on smaller screen) I need to show only 1 or 2 or some other number calculated by the length of the Autocomplete.
- If the selected option titles are too long, than show just one for example. And if they are short, show maybe even more than 3. This should be calculated by length of shown tag titles.
Is this possible?
I am using example code:
<Autocomplete
multiple
id="tags-standard"
options={top100Films}
getOptionLabel={(option) => option.title}
limitTags={3}
disableCloseOnSelect
defaultValue={[top100Films[13]]}
renderInput={(params) => (
<TextField
{...params}
variant="standard"
label="Multiple values"
placeholder="Favorites"
/>
)}
/>
2
Answers
For such purpose you have the property called
renderTags
. Docs: https://mui.com/material-ui/api/autocomplete/#autocomplete-prop-renderTagsYou can try something like this (omitting other Autocomplete values for brevity). -1 for limitTags is the default value.
This requires listening window
resize
event, Autocomplete value change event as well as calculating the widths of selected items by usingref
.You can use this code to handle all those requirements:
You can take a look at this StackBlitz for a live working example of this answer.