Search code examples
reactjsmaterial-uiautocomplete

MUI Autocomplete does not fully appear in AppBar


I am trying to put an MUI Autocomplete select field inside an AppBar component and it does not work as expected when onFocus. Specifically, the label appears behind the AppBar and the border disappears.

In order to reproduce it, I created this codesandbox. It is built over the MUI demo of an AppBar with text field. And created an additional AppBar with Autocomplete field.

My questions are:

  1. Any idea what causes this and how to fix it?
  2. I am fairly new to MUI. Which classes should I override in the Autocomplete component in order to make it look like the text field in this example?

Thanks in advance for any assistance.

enter image description here


Solution

  • Answers to your questions:

    1. You can fix this floating label by replacing label prop on TextField with placeholder prop.
    2. Since you are using styled components, you can inspect the elements and find out the selectors to use within styled component.

    I've modified your codesandbox and added following changes.

    <Autocomplete
            disablePortal
            id="combo-box-demo"
            options={top100Films}
            sx={{ width: { xs: "100%", sm: "20ch" }, borderWidth: "0px" }}
            renderInput={(params) => (
              <StyledTextField
                {...params}
                placeholder="Search..."
                size="small"
                InputProps={{
                  ...params.InputProps,
                  startAdornment: (
                    <InputAdornment position="start">
                      <SearchIcon
                        style={{ color: "white", marginLeft: "8px" }}
                      />
                    </InputAdornment>
                  )
                }}
              />
            )}
    />
    

    Below is the code for StyledTextField component

    const StyledTextField = styled(TextField)(({ theme }) => ({
      color: "#fff",
      background: "rgba(255, 255, 255, 0.15)",
      borderRadius: "4px",
      width: "100%",
      "& input": {
        color: "#fff !important"
      },
      "& fieldset": {
        borderWidth: "0px",
        "& fieldset:hover, & fieldset:focus, & fieldset:active": {
          borderWidth: "0px"
        },
        "& .MuiInputBase-input": {
          padding: theme.spacing(2, 1, 1, 2),
          transition: theme.transitions.create("width"),
          color: "#fff",
          width: "100%",
          [theme.breakpoints.up("sm")]: {
            width: "12ch",
            "&:focus": {
              width: "20ch"
            }
          }
        }
      }
    }));
    

    Here is the updated codesandbox

    Hope this helps you.