Material UI 範例

使用 Material UI (MUI) 元件搭配 Google Material Design 的範例。

基本下拉選單

使用 MUI Select 的簡單國家下拉選單。注意:此元件不支援篩選功能,如需篩選請使用 Autocomplete。

常用國家置頂

常用國家固定在頂部,使用 ListSubheader 區隔。

可搜尋自動完成

核心功能!輸入英文即可篩選中文國家名稱。試著輸入「united」來找到美國和英國。

排序選項

可切換筆畫順序、英文字母順序或注音順序排序。

國旗開關

切換國旗表情符號的顯示與隱藏。

國家白名單

限制只顯示特定國家(例如:亞洲國家)。

Showing only Asian countries (13 countries)

程式碼範例

import { useCountryList } from 'use-country-list-zh';
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';

function CountryAutocomplete() {
  const {
    countries,
    query,
    setQuery,
    selectedCountry,
    setSelectedCountry,
    getDisplayText,
  } = useCountryList({
    showFlag: true,
    topList: ['TW', 'US', 'JP'],
  });

  return (
    <Autocomplete
      options={countries}
      value={selectedCountry}
      onChange={(_, newValue) => setSelectedCountry(newValue)}
      inputValue={query}
      onInputChange={(_, newValue) => setQuery(newValue)}
      getOptionLabel={(option) => getDisplayText(option)}
      isOptionEqualToValue={(option, value) => option.code === value.code}
      groupBy={(option) => option.isTop ? 'Popular' : 'All Countries'}
      renderInput={(params) => (
        <TextField {...params} label="Select a country" />
      )}
      filterOptions={(x) => x} // Use hook's filtering
    />
  );
}