How can I add an icon to Material-UI Select?
Asked Answered
I

2

6

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.

enter image description here

enter image description here

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>
Inquiry answered 24/9, 2021 at 13:18 Comment(1)
check this example linkTosspot
D
11

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>
    );
  }}
  {...}
>

Live Demo

Codesandbox Demo

Diseased answered 24/9, 2021 at 13:43 Comment(1)
Hi, it does work properly when the value and the showed element are the same, but how to do when they are differently? Example: {elencoEsercizi.map(option => <MenuItem key={option.id} value={option.id}> {option.NameOfItem}</MenuItem> )} any suggestion ? Thanks !Alexanderalexandr
H
0

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

Hiccup answered 4/4 at 17:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.