190303458
190303458

Reputation: 63

How to add a placeholder to MUI Select component created by TextField?

I want to add a placeholder (-- Select --) to the following MUI Select component created by TextField with select prop.

const [country, setCountry] = useState("")

<TextField
    select
    value={country}
    onChange={e => setCountry(e.target.value)}
>
    <MenuItem value='US'>America</MenuItem>
    <MenuItem value='CA'>Canada</MenuItem>
    <MenuItem value='UK'>England</MenuItem>
</TextField>

I've tried to add placeholder='-- Select --' props but the placeholder can't be displayed.

Then I've tried to add label='-- Select --' props. Although the placeholder can be displayed, when the component was rendered initially and I tried to select an option, the label moved to the top-left corner of the component, I don't want that animation. Then I've tried to add InputLabelProps={{disableAnimation: true}} props but the animation still existed.

Could someone teach me how to add a placeholder in my case?

Upvotes: 2

Views: 1740

Answers (1)

Ahmet Emre Kilinc
Ahmet Emre Kilinc

Reputation: 6885

If we inspect the Select element, there is an empty span inside the div with the class .MuiSelect-select which is visible when there is no value selected.

enter image description here

We can create a work-around solution using this span like this:

const [country, setCountry] = useState('');

return (
    <TextField
      sx={{
        width: '300px',
        '& .MuiSelect-select span::before': {
          content: "'-- Select --'",
        },
      }}
      select
      value={country}
      onChange={(e) => setCountry(e.target.value)}
    >
      <MenuItem value="US">America</MenuItem>
      <MenuItem value="CA">Canada</MenuItem>
      <MenuItem value="UK">England</MenuItem>
    </TextField>
);

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

Upvotes: 2

Related Questions