Textfield position shifts up after making a selection MUI?

Viewed 102

I have this Autocomplete component, it renders a TextField with options to select from , problem is once I make a selection, it losses margin top, my bet is on the text, since there is no text there is no margin! I partially solved it by add in a empty space, which proves my point but still what is the right way to solve this, any idea how to stop this from happening and yet be able to pass an empty text without losing the margin.

Codesandbox Example

2 Answers

The reason it doesn't work is because of the label, you set the label to an empty string whenever there is a selected value:

label={selected.item === "" ? "test" : ""}

Which affects the following rule:

label + .MuiInput-formControl {
    margin-top: 16px;
}

If the label is empty, it will be removed from the DOM, so margin-top doesn't get applied anymore. A simple workaround is simply set the label to a non-empty string even if you don't want to display it:

label={selected.item === "" ? "test" : " "}

Codesandbox Demo

You can use placeholder props to the TextField component inside Autocomplete rather than conditional label props.

And then if you want to add margin, you can add some styling to the Autocomplete component like style={{marginTop:20}} or using MUI makeStyles API. https://v4.mui.com/styles/api/#makestyles-styles-options-hook

      ...
      <Autocomplete
        id="combo-box-demo"
        key={bool}
        options={arr}
        getOptionLabel={(option) => option}
        onChange={handleChange}
        style={{marginTop: 20}} // or using makeStyles
        renderInput={(params) => (
          <TextField
            {...params}
            placeholder="test" //label="test"
          />
        )}
      />
      ...
Related