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?
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.

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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With