How can I add an icon to Material UI Select options?

核能气质少年 提交于 2021-02-08 14:26:56

问题


how to add icon inside Select options I made many tries none of them are working

 <option value={0}>&#xf083;Item One</option>
        <option value={1}>
          <i class="fas fa-expand" />
          Item two
        </option>

full sample code

class IconInSelect extends Component {
  state = {
    value: 0
  };
  handleChange = name => event => {
    this.setState({ [name]: event.target.value });
  };
  render() {
    const { value } = this.state;
    const { classes } = this.props;
    return (
      <Select
        autoWidth
        native
        value={value}
        onChange={this.handleChange("value")}
        name="value"
        variant="filled"
        classes={{
          root: classes.selectEmpty,
          select: classes.select
        }}
      >
        <option value={0}>&#xf083;Item One</option>
        <option value={1}>
          <i class="fas fa-expand" />
          Item two
        </option>
        <option value={2}>Item three</option>
      </Select>
    );
  }
}

codesandbox any help approached


回答1:


Use MenuItem.

class IconInSelect extends Component {
  ...
  render() {
    return (
      <Select>
        <MenuItem value="">
          <ListItemIcon>
            <InboxIcon />
          </ListItemIcon>
          <ListItemText primary="Inbox" />
        </MenuItem>
        <MenuItem value={10}>Ten</MenuItem>
        <MenuItem value={20}>Twenty</MenuItem>
        <MenuItem value={30}>Thirty</MenuItem>
      </Select>
    );
  }
}




回答2:


This works better without line-break when selected

<MenuItem value={10}>
    <div style={{ display: 'flex', alignItems: 'center' }}>
        <InboxIcon />
        <div>Inbox</div>
    </div>
</MenuItem>

Just use custom styling in InboxIcon and set margin according to your need



来源:https://stackoverflow.com/questions/56115799/how-can-i-add-an-icon-to-material-ui-select-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!