Search code examples
reactjsmaterial-uitextfieldadornment

Material UI: StartAdornment is not working with label


The standard variant of 'TextField' is not working as expected if 'StartAdornment' is added with an icon.

If I add StartAdornment the label remains up. I want the label should work as placeholder and goes up when the focus is in TextField.

Here is the SandBox link:


export const Temp = () => {
  return (
    <div>
      <Grid sx={{ mt: 1.5 }}>
        <TextField
          variant="standard"
          required
          fullWidth
          label="Enter Mobile Number"
          autoFocus
          InputProps={{
            startAdornment: (
              <LoginRoundedIcon
                sx={{ p: 0.25, color: "#A9A9A9", ml: -0.5, mr: 1 }}
                position="start"
              >
                <Visibility></Visibility>
              </LoginRoundedIcon>
            ),
          }}
        />
      </Grid>
    </div>
  );
};

enter image description here


Solution

  • This is a limitation that we can overcome with a work-around like this:

    const [focused, setFocused] = useState(false);
    const [currentValue, setCurrentValue] = useState("");
    
    
    <TextField
          variant="standard"
          required
          fullWidth
          label="Enter Mobile Number"
          InputProps={{
            startAdornment: (
              <LoginRoundedIcon
                sx={{ p: 0.25, color: "#A9A9A9", ml: -0.5, mr: 1 }}
                position="start"
              >
                <Visibility></Visibility>
              </LoginRoundedIcon>
            )
          }}
          InputLabelProps={{
            shrink: focused || currentValue,
            style: { marginLeft: 30 }
          }}
          value={currentValue}
          onChange={(e) => setCurrentValue(e.target.value)}
          onFocus={() => setFocused(true)}
          onBlur={() => setFocused(false)}
    />
    

    You can take a look at this stackblitz for a live working example of this work-around.