Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reactjs - How to properly add icon to select options in Material UI?

I was trying to set an icon for each Select option in Material UI. I followed the answer proposed in this question How can I add an icon to Material UI Select options? using ListItemIcon and ListItemText, and it indeed shows the icon for each option but, when selected, the icon is shown alongside the option value on a different line. The image shows what I mean by this.

Example of icon and text value once the option is selected

What can I do to make it so that just the text is shown in one single line and no icon is displayed when I select an option? I'll attach here the code that I used for reference.

import React, { useState } from "react";
import {
  Box,
  Select,
  MenuItem,
  ListItemIcon,
  ListItemText,
} from "@material-ui/core";
import ShortTextIcon from "@material-ui/icons/ShortText";
import SubjectIcon from "@material-ui/icons/Subject";
import { makeStyles } from "@material-ui/core/styles";

const useStyles = makeStyles({
  root: {
    textAlign: "center",
  },
});

function App() {
  const classes = useStyles();

  const [state, setState] = useState("");

  const handleChange = (e) => {
    setState(e.target.value);
  };

  return (
    <Box component="div" className={classes.root}>
      <Select value={state} onChange={handleChange}>
        <MenuItem value="First Choice">
          <ListItemIcon>
            <ShortTextIcon />
          </ListItemIcon>
          <ListItemText primary="First Choice" />
        </MenuItem>
        <MenuItem value="Second Choice">
          <ListItemIcon>
            <SubjectIcon />
          </ListItemIcon>
          <ListItemText primary="Second Choice" />
        </MenuItem>
      </Select>
    </Box>
  );
}

export default App;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use renderValue property of Select API it allows you to render whatever you want as a value with signature: function(value: any) => ReactNode where value is current selected value of select. (This can be used only if native prop is false)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...