Material-UI: How to add Icons in the TextField label?

Viewed 3126

I am trying to add Material-UI icons into TextField component, I want to add it to the label not in input Field.

Eg:

through Inputprops we can pass and add icon to input, but I want it in label. How to achieve this..?

<Field label="Name" required /> -> Name*

What I want to achieve is:

<Field label="Name" required /> -> Name*(icon)
2 Answers

It can be achieved by using flex and order properties of CSS, lightweight and effective.

Result:

enter image description here enter image description here

Full code sample :

Edit TextField selectionStart

Code fragment :

const useStyles = makeStyles({
  root: {
    "& .MuiFormLabel-root": {
      display: "flex",
      alignItems: "center",
      "& .myIcon": {
        paddingLeft: "8px",
        order: 999
      }
    }
  }
});

const Demo = () => {
  const classes = useStyles();
  return (
    <TextField
      className={classes.root}
      required
      label={
        <Fragment>
          I am label
          <SettingsRounded className="myIcon" fontSize="small" />
        </Fragment>
      }
      variant="outlined"
    />
  );
};

Hope to help you !

Because label can accept a ReactNode, you add an icon component to the TextField like this:

import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Add from "@material-ui/icons/Add";
const useStyles = makeStyles({
  root: {
    "& label": {
      marginTop: -3, // fix the icon alignment issue
    }
  },
  label: {
    display: "inline-flex",
    alignItems: "center"
  }
});

export default function BasicTextFields() {
  const classes = useStyles();

  return (
    <TextField
      className={classes.root}
      label={
        <div className={classes.label}>
          <span>My Label</span>
          <Add />
        </div>
      }
      variant="outlined"
    />
  );
}

Live Demo

Edit 67056371/how-to-add-icons-in-material-ui-textfield-label

Related