I am using Autocomplete to select a country flag in my React app. When a country is selected, I want to display the selected country flag, but it only displays the country name. How can I display the selected country flag along with the country name?
I provide my current code:
export default function CountrySelect({selectedCountry, onChange}) {
return (
<Autocomplete
value={selectedCountry}
onChange={onChange}
id="country-select"
options={countries}
autoHighlight
getOptionLabel={(option) => option.label}
renderOption={(props, option) => (
<Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
<img
loading="lazy"
width="20"
srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
alt=""
/>
{option.label} ({option.code}) +{option.phone}
</Box>
)}
renderInput={
<TextField
{...params}
placeholder="Select a country"
/>
}
/>
);
}
I tried updating renderOption but that didn't work.
I found the solution and it's customizing renderInputs based on selected country. I provide my solution code.
export default function CountrySelect({selectedCountry, onChange}) {
const renderInput = (params: any) => {
return (
<TextField
{...params}
placeholder="Select a country"
InputProps={{
...params.InputProps,
startAdornment: (selectedCountry != null && selectedCountry != undefined && selectedCountry != '') ? (
<img
src={`https://flagcdn.com/w20/${selectedCountry?.code?.toLowerCase()}.png`}
alt={selectedCountry?.label}
style={{
margin: 0,
paddingLeft: '16px'
}}
/>
) : null
}}
/>
)
};
return (
<Autocomplete
value={selectedCountry}
onChange={onChange}
id="country-select"
options={countries}
autoHighlight
getOptionLabel={(option) => option.label}
renderOption={(props, option) => (
<Box component="li" sx={{ '& > img': { mr: 2, flexShrink: 0 } }} {...props}>
<img
loading="lazy"
width="20"
srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
alt=""
/>
{option.label} ({option.code}) +{option.phone}
</Box>
)}
renderInput={renderInput}
/>
);
}
Thank you all.