I am currently working on incorporating the Material-UI Autocomplete component, and my goal is to have each option label show an icon along with some text. The challenge I'm facing is that I only want the popper element to be the width of the text input, with any overflowing text displaying ellipsis. In my renderOption method, if I use
<Typography noWrap>"Text"</Typography>
, it successfully adds an ellipsis to the text. However, when I try to include this in a Grid or Flex box along with the icon, the Popper component ends up having horizontal scroll. Is there a way to ensure that the Popper viewport stays constrained to the Autocomplete width so that the text in the renderOption method wraps properly?
import React from 'react';
import InputAdornment from '@material-ui/core/InputAdornment';
import TextField from '@material-ui/core/TextField';
import SearchIcon from '@material-ui/icons/Search';
import PersonIcon from '@material-ui/icons/Person';
import GraphicEqIcon from '@material-ui/icons/GraphicEq';
import { Grid } from '@material-ui/core';
import { Autocomplete } from '@material-ui/lab';
import Typography from '@material-ui/core/Typography';
function SearchBarDisplay({ options = [], onChange, onSelectValue, value = '' }) {
function getOptionLabel(option) {
if (option.name) {
return option.name;
} else if (option.username) {
return option.username;
} else if (option.type === 'advanced') {
return option.value;
} else {
return null;
}
}
function renderOption(name, username, type) {
if (name) {
return (
<Grid container alignItems="center" spacing={1} wrap={'nowrap'}>
<GraphicEqIcon />
<Grid item>
<Typography noWrap>{name}</Typography>
</Grid>
</Grid>
);
} else if (username) {
return (
<Grid container alignItems="center" spacing={1} wrap={'nowrap'}>
<PersonIcon />
<Grid item>
<Typography noWrap>{username}</Typography>
</Grid>
</Grid>
);
} else if (type === 'advanced') {
return (
<Grid container alignItems="center" spacing={1}>
<SearchIcon />
<Grid item>
<Typography
noWrap={true}
color="textSecondary">{`See more results for "${value}"`}</Typography>
</Grid>
</Grid>
);
} else {
return null;
}
}
return (
<Autocomplete
id="autocomplete"
options={options}
getOptionSelected={(option, value) => option._id === value._id}
getOptionLabel={(option) => getOptionLabel(option)}
onChange={(event, value) => {
onSelectValue(value);
}}
onInputChange={(event, value) => onChange(value)}
renderOption={({ name, username, type }) => renderOption(name, username, type)}
renderInput={(params) => (
<TextField
{...params}
placeholder="Search for podcasts or users"
margin="normal"
variant="outlined"
InputProps={{
...params.InputProps,
startAdornment: (
<>
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
</>
)
}}
/>
)}
/>
);
}
export default SearchBarDisplay;