Reputation: 877
I need to add a location icon to react Material-UI Select
options. But there is no option for that...I read API docs in select but can't find a related option. So I really need your help with that. Thank you very much.
I found code like this. but not working properly.
<div id='location-box'>
<Select>
<MenuItem value="">
<ListItemIcon>
<LocationOnIcon />
</ListItemIcon>
<ListItemText primary="Inbox" />
</MenuItem>
<MenuItem value={10}>Ten</MenuItem>
<MenuItem value={20}>Twenty</MenuItem>
<MenuItem value={30}>Thirty</MenuItem>
</Select>
</div>
Upvotes: 6
Views: 14637
Reputation: 3381
You can use Material-UI's Autocomplete component. It behaves much like a Select and provides an event allowing you to specify the layout of each option. Here's an example of how to use it:
<Autocomplete
id="country-select-demo"
sx={{ width: 300 }}
options={countries}
autoHighlight
getOptionLabel={(option) => option.label}
renderOption={(props, option) => (
<Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
<img
loading="lazy"
width="20"
srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
alt=""
/>
{option.label} ({option.code}) +{option.phone}
</Box>
)}
renderInput={(params) => (
<TextField
{...params}
label="Choose a country"
inputProps={{
...params.inputProps,
autoComplete: 'new-password'
}}
/>
)}
/>
You can see documentation on that here: https://mui.com/material-ui/react-autocomplete/#country-select
Upvotes: 0
Reputation: 81833
You can override the renderValue
callback to render the selected text with whatever icon you want. Remember to set displayEmpty
to force the Select
display an empty value if no option is selected. For reference, see the full list of API here:
<Select
displayEmpty
renderValue={(value) => {
return (
<Box sx={{ display: "flex", gap: 1 }}>
<SvgIcon color="primary">
<LocationOnIcon />
</SvgIcon>
{value}
</Box>
);
}}
{...}
>
Upvotes: 11