javascriptreactjsmaterial-uimui-autocomplete

Material UI autocomplete in dialog placeholder fix delay


I'm using Material UI autocomplete textfield in my project inside a dialog. The problem is, when i set a defaultValue or a first value, you can see the placeholder moving on the opening of the dialog.

https://codesandbox.io/embed/material-ui-autocomplete-forked-xwd3k?fontsize=14&hidenavigation=1&theme=dark

Here is the code

import React from "react";
import ReactDOM from "react-dom";
import Autocomplete from "@material-ui/lab/Autocomplete";
import { TextField } from "@material-ui/core";
import DialogTitle from "@material-ui/core/DialogTitle";
import Dialog from "@material-ui/core/Dialog";
import Button from "@material-ui/core/Button";

import "./styles.css";

function App() {
  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = (value) => {
    setOpen(false);
  };

  return (
    <>
      <Dialog
        onClose={handleClose}
        aria-labelledby="simple-dialog-title"
        open={open}
      >
        <DialogTitle id="simple-dialog-title">Set backup account</DialogTitle>
        <Autocomplete
          freeSolo
          id="free-solo-demo"
          defaultValue={"a"}
          options={["a", "b", "c"]}
          renderInput={(params) => (
            <TextField
              {...params}
              label="freeSolo"
              margin="normal"
              variant="outlined"
              fullWidth
            />
          )}
        />
      </Dialog>
      <div>
        <br />
        <Button variant="outlined" color="primary" onClick={handleClickOpen}>
          Open simple dialog
        </Button>
      </div>
    </>
  );
}

Is there a way to see the placeholder already fixed when the dialog is open? I have an other autocomplete that is with multiple, and this textfield is not giving me this error at all.


Solution

  • Add the following InputLabelProps to the TextField component.

    <TextField
      {...params}
      InputLabelProps={{ // this part
        shrink: true
      }}
      label="freeSolo"
      margin="normal"
      variant="outlined"
      fullWidth
    />              
    

    If you check the implementation of the TextField component, you can see that the input label prop gets notched if the shrink parameter is truthy.

    Edit: Which means that if the field becomes empty you will have to manage that yourself.