Reputation: 1611
I have a React MUI Autocomplete component as the one from the official doc.
The following is the example for the countries.
import * as React from 'react';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';
export default function CountrySelect() {
return (
<Autocomplete
id="country-select-demo"
sx={{ width: 300 }}
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"
src={`https://flagcdn.com/w20/${option.code.toLowerCase()}.png`}
srcSet={`https://flagcdn.com/w40/${option.code.toLowerCase()}.png 2x`}
alt=""
/>
{option.label} ({option.code}) +{option.phone}
</Box>
)}
renderInput={(params) => (
<TextField
{...params}
label="Choose a country"
inputProps={{
...params.inputProps,
autoComplete: 'new-password', // disable autocomplete and autofill
}}
/>
)}
/>
);
}
// From https://bitbucket.org/atlassian/atlaskit-mk-2/raw/4ad0e56649c3e6c973e226b7efaeb28cb240ccb0/packages/core/select/src/data/countries.js
const countries = [
{ code: 'AD', label: 'Andorra', phone: '376' },
..........
..........
{
code: 'AE',
label: 'United Arab Emirates',
phone: '971',
},
];
During the selection, the component show a list of countries alongside some info and the corresponding icon flag.
After picking a country, the country's name is displayed in the Textfield.
From what I understood from this post, it is possible to manipulate the property renderInput in order to customize the final appeareance of the component, in this example the TextField.
Is there a way to display also the flag near the selected country name?
Upvotes: 1
Views: 2534
Reputation: 2433
To show the icon of a selected option, you should add start startAdornment
to InputProps
of TextField
component. This prop is responsible for rendering icon before the text of selected option. Then we can pass the property of a selected option to startAdornment
to show the icon of the selected option:
<Autocomplete
value={value}
onChange={(event, newValue) => {
setValue(newValue);
}}
renderInput={(params) => {
return (
<TextField
{...params}
label="Choose a country"
inputProps={{
...params.inputProps,
autoComplete: "new-password"
}}
InputProps={{
...params.InputProps,
startAdornment: value ? (
<InputAdornment position="start">
<img
loading="lazy"
width="20"
src={`https://flagcdn.com/w20/${value.code.toLowerCase()}.png`}
srcSet={`https://flagcdn.com/w40/${value.code.toLowerCase()}.png 2x`}
alt=""
/>
</InputAdornment>
) : null
}}
/>
);
}}
... other props
Upvotes: 1