MUICountrySelect
MUICountrySelect is an
Autocomplete pre-loaded with
a list of 250 countries (flag, name, ISO and ISO3 code). Store
the complete CountryDetails object, or a single property via valueKey. Pin
common choices with preferredCountries.
Usage
import MUICountrySelect, {
MUICountrySelectProps,
CountryISO,
CountryDetails,
countryList
} from '@nish1896/mui-components/mui/country-select';Without a valueKey, value is the whole CountryDetails object, or
null when nothing is selected:
const [country, setCountry] = useState<CountryDetails | null>(null);
<MUICountrySelect
fieldName="country"
value={country}
onValueChange={({ newValue, event, reason, details }) => setCountry(newValue)}
/>onValueChange receives { newValue, event, reason, details }: the value to
store, the original change event, and Material UI's change reason and
details.
Country data
Each country is an object with a name, an iso code, an iso3 code and an
emoji flag:
{
name: 'India',
iso: 'IN',
iso3: 'IND',
emoji: '🇮🇳'
}The iso key is strongly typed as CountryISO, which keeps
preferredCountries and your own code type safe. The full list of 250 countries
is exported as countryList, so you can read or filter it yourself. Its data
comes from this countries database.
Choosing the stored value
Set valueKey to store a single property of the country instead of the whole
object. It can be iso, iso3 or name.
valueKey | Stored value for India |
|---|---|
| none | { name: 'India', iso: 'IN', iso3: 'IND', emoji: '🇮🇳' } |
iso | 'IN' |
iso3 | 'IND' |
name | 'India' |
const [country, setCountry] = useState<string | null>(null);
/* newValue is "IND" for India, "AUS" for Australia */
<MUICountrySelect
fieldName="country"
valueKey="iso3"
value={country}
onValueChange={({ newValue }) => setCountry(newValue)}
/>The stored value is also how a country is matched. With a valueKey, a country
is matched by that property, and a stored value that isn't in the list isn't
shown as selected.
When valueKey is omitted, countries are matched by iso, so an object loaded
from your API matches as long as its iso is the same. Clearing the field gives
null, or [] with multiple, unless disableClearable is set.
Customizing the country list
By default every country in countryList is listed in the options.
Pass countries prop to only render the ones that are required.
const filteredCountries = countryList.filter(country => (
['IN', 'US', 'AU', 'FI', 'UA', 'CN', 'GB', 'JP', 'VN'].includes(country.iso)
));preferredCountries pins countries to the top of the dropdown, by iso code.
They appear in the order you list them, followed by the remaining countries in
their usual order. A pinned country isn't repeated further down, and a code that
isn't in the list is ignored. It only changes the order of the options, not the
value.
<MUICountrySelect
fieldName="dreamDestinations"
countries={filteredCountries}
preferredCountries={['IN', 'AU', 'JP']}
valueKey="name"
multiple
/>Multiple selection
Set multiple to store an array: of whole country objects, or of the
valueKey property when one is set. Each selection is shown as a chip,
and the menu stays open while the user picks.
While the field is not focused, only the first limitTags chips (default 2)
are shown, followed by a chip such as "+1 Country" or "+3 Countries".
limitTags={-1} shows all of them, and getLimitTagsText receives the
number of hidden chips and returns your own text.
ChipProps customizes the chips.
const [countries, setCountries] = useState<string[]>([]);
<MUICountrySelect
fieldName="countriesVisited"
valueKey="iso"
value={countries}
onValueChange={({ newValue }) => setCountries(newValue)}
multiple
limitTags={3}
getLimitTagsText={hidden => `+${hidden} more`}
ChipProps={{ color: 'primary', size: 'small' }}
/>Custom option labels
Each option shows the country's flag and name by default.
renderOptionLabel replaces that content. It receives the
country and a state object with selected, index, inputValue
and disabled.
<MUICountrySelect
fieldName="country"
value={country}
onValueChange={({ newValue }) => setCountry(newValue)}
renderOptionLabel={(option, { selected }) => (
<span style={{ fontWeight: selected ? 700 : 400 }}>
{option.emoji} {option.name} ({option.iso3})
</span>
)}
/>Input and behavior
textFieldProps is forwarded to the underlying TextField, for example a
placeholder, variant or size. autoHighlight is true by default, so the
first match is highlighted as the user types and Enter selects it.
disableClearable removes the clear button, and a ref gives you the input
element. Only countries from the list can be selected, so freeSolo is not
supported.
API
Pass valueKey (e.g. iso or name) to store a single country property
instead of the full object.
Props marked with * are required.
| Name | Type | Description |
|---|---|---|
fieldName* | string | Name/path of the field. Used to derive the id, the default label, and the name attribute. This prop is required for all components. |
countries | CountryDetails[] | List of countries to display in the country selector. Defaults to all countries from countryList. |
preferredCountries | CountryISO[] | Country ISO codes pinned at the top of the dropdown, in the provided order. |
valueKey | `name` | `iso` | `iso3` | When provided, selected value(s) are exposed using the specified country property; when omitted, complete country objects are used. |
ref | Ref<HTMLInputElement> | Forwarded ref for the underlying MUI TextField's input element — use it to imperatively focus the field or read its DOM node. |
value | CountryDetails | CountryDetails[keyof CountryDetails] | array | null | Currently selected country value(s): complete CountryDetails object(s), or the property named by valueKey when provided. Pass an array when multiple is true. A cleared single selection emits null (unless disableClearable); a cleared multi-selection emits [], never null. |
onValueChange* | ({ newValue, event, reason, details }) => void | Called on every selection change with the normalized country value and the raw MUI Autocomplete change metadata. |
multiple | boolean | When true, allows selecting multiple values. |
disableClearable | boolean | When true, the selected value cannot be cleared from the input.Default: false |
renderOptionLabel | (option: CountryDetails) => ReactNode | Custom renderer for each country option in the dropdown. Receives the country object and should return the label/content to render. |
limitTags | number | Maximum number of selected values shown as chips when the input is not focused. Set -1 to disable the limit.Default: 2 |
getLimitTagsText | (more: number) => ReactNode | Custom label rendered for the hidden selections counter. Receives the number of hidden values. |
textFieldProps | TextFieldProps | TextFieldProps forwarded to the internal MUI TextField. |
ChipProps | ChipProps | ChipProps forwarded to chips rendered for selected values. |
label | ReactNode | Label displayed for the field. Defaults to a human-readable label derived from fieldName, e.g. firstName becomes "First Name". |
showLabelAboveFormField | boolean | When true, renders the field label above the form field in the FormLabel component, instead of inside or beside it. Takes precedence over allLabelsAboveFields from the ConfigProvider, so false keeps the label inside this field even when the config places every label above its field. |
formLabelProps | FormLabelProps | FormLabelProps forwarded to the internal FormLabel. The id is managed by the component. Multiple fields can be configured using the ConfigProvider component. |
hideLabel | boolean | When true, hides the rendered field label while preserving accessible labeling where possible. |
required | boolean | Indicates that the field is mandatory by adding an asterisk symbol (*) to the form label and setting the relevant accessibility attributes. |
errorMessage | string | string[] | Validation error for the field — pass a single message string, or a string[] when the field can fail multiple rules at once (every message is shown together). A non-empty string or array puts the field in an error state; undefined/''/[] clear it.Normalize your form library's error shape to this at the call site (e.g. an RHF FieldError via its .message). Use renderError to customize how the message(s) are rendered. |
renderError | (errors: string[]) => ReactNode | Custom renderer for the resolved error message(s), called only when the field is in an error state. Always receives a string[] — use errors[0] for the common single-message case, or map over errors when a field fails several rules. By default a single message renders as text and multiple messages render on separate lines. |
hideErrorMessage | boolean | If true, hides the error message text while keeping the field in an error state. |
helperText | ReactNode | Content displayed in the FormHelperText component below the field when there is no visible validation error. |
formHelperTextProps | FormHelperTextProps | FormHelperTextProps forwarded to the internal FormHelperText. The id is managed by the component. Multiple fields can be configured using the ConfigProvider component. |
customIds | { field, label, helperText, error } | Overrides the default field, label, helper text, and error IDs used for accessibility. |
Playground
Driven by plain React state — a single select with preferredCountries and a
flag renderOptionLabel, and a multi-select with limitTags and ChipProps.
Reference
Source Code
View the full implementation of this component on GitHub.