Gathering detailed insights and metrics for country-flags-util
Gathering detailed insights and metrics for country-flags-util
Gathering detailed insights and metrics for country-flags-util
Gathering detailed insights and metrics for country-flags-util
@nzz/et-utils-country-flags
Library to insert country flags
@wemnyelezxnpm/odio-aspernatur-rem
`@wemnyelezxnpm/odio-aspernatur-rem` is an npm package designed to provide extensive information about countries, encompassing details such as country code, name, currency symbol, capital city, phone code, latitude, and longitude.
npm install country-flags-util
Typescript
Module System
Min. Node Version
Node Version
NPM Version
JavaScript (100%)
Total Downloads
271
Last Day
1
Last Week
52
Last Month
271
Last Year
271
MIT License
4 Commits
1 Watchers
1 Branches
1 Contributors
Updated on May 11, 2025
Minified
Minified + Gzipped
Latest Version
1.0.1
Package Id
country-flags-util@1.0.1
Unpacked Size
68.08 kB
Size
14.30 kB
File Count
10
NPM Version
11.1.0
Node Version
23.9.0
Published on
May 11, 2025
Cumulative downloads
Total Downloads
Last Day
0%
1
Compared to previous day
Last Week
0%
52
Compared to previous week
Last Month
0%
271
Compared to previous month
Last Year
0%
271
Compared to previous year
No dependencies detected.
A comprehensive utility library for working with countries, flag emojis, flag images, and generating country select dropdowns across various frameworks.
1npm install country-flags-util
1const { 2 getAllCountries, 3 getFlagEmoji, 4 getFlagImageUrl, 5 getCountrySelect 6} = require('country-flags-util'); 7 8// Get all countries with their flags 9const countries = getAllCountries(); 10console.log(countries[0]); // { name: "Afghanistan", code: "AF", flag: "🇦🇫" } 11 12// Get flag emoji for a specific country code 13const usFlag = getFlagEmoji('US'); 14console.log(usFlag); // 🇺🇸 15 16// Get flag image URL from flagcdn.com 17const ukFlagUrl = getFlagImageUrl('GB', 80); 18console.log(ukFlagUrl); // https://flagcdn.com/w80/gb.png 19 20// Generate HTML for a country select dropdown with image flags (default) 21const selectHTML = getCountrySelect({ 22 id: 'my-countries', 23 name: 'country-selector', 24 className: 'form-control', 25 selectedCode: 'CA' 26}); 27 28// Generate HTML for a country select dropdown with emoji flags 29const emojiSelectHTML = getCountrySelect({ 30 selectedCode: 'JP', 31 useImageFlags: false 32});
getAllCountries()
Returns an array of objects containing country information.
Returns:
Array<Object>
: Array of country objects with the following properties:
name
(String): The country namecode
(String): The 2-letter ISO country codeflag
(String): The emoji flag for the countryExample:
1const countries = getAllCountries(); 2// [ 3// { name: "Afghanistan", code: "AF", flag: "🇦🇫" }, 4// { name: "Åland Islands", code: "AX", flag: "🇦🇽" }, 5// ... 6// ]
getFlagEmoji(code)
Converts a 2-letter ISO country code to an emoji flag.
Parameters:
code
(String): The 2-letter ISO country code (e.g., "US", "IN")Returns:
String
: The flag emoji or an empty string if the code is invalidExample:
1const flag = getFlagEmoji('JP'); 2console.log(flag); // 🇯🇵
getFlagImageUrl(code, width)
Gets the flag image URL from flagcdn.com.
Parameters:
code
(String): The 2-letter ISO country code (e.g., "US", "IN")width
(Number, optional): The width of the flag image in pixels (default: 40)Returns:
String
: URL to the flag image or an empty string if the code is invalidExample:
1const flagUrl = getFlagImageUrl('DE', 80); 2console.log(flagUrl); // https://flagcdn.com/w80/de.png
getCountrySelect(options)
Generates HTML for a select dropdown with country flags and names.
Parameters:
options
(Object, optional): Configuration object with the following properties:
id
(String): HTML id attribute for the select element (default: 'country-select')name
(String): HTML name attribute for the select element (default: 'country')className
(String): HTML class attribute for the select element (default: '')selectedCode
(String): Country code to be selected by default (default: '')useImageFlags
(Boolean): Whether to use image flags instead of emoji flags (default: true)flagWidth
(Number): Width of flag images in pixels (default: 40)Returns:
String
: HTML string for the country select dropdownExample:
1const html = getCountrySelect({ 2 id: 'my-country-select', 3 className: 'form-control', 4 selectedCode: 'FR', 5 useImageFlags: true, 6 flagWidth: 30 7});
The React module provides functions to generate JSX code and full React components.
1import React, { useState, useRef, useEffect } from 'react'; 2import { getAllCountries, getFlagImageUrl, getFlagEmoji } from 'country-flags-util'; 3 4export default function CountrySelectPage() { 5 const [selectedCountry, setSelectedCountry] = useState(''); 6 const [useImageFlags, setUseImageFlags] = useState(true); 7 const [enableSearch, setEnableSearch] = useState(true); 8 const [isDropdownOpen, setIsDropdownOpen] = useState(false); 9 const [searchTerm, setSearchTerm] = useState(''); 10 const countries = getAllCountries(); 11 const dropdownRef = useRef(null); 12 const selectedItemRef = useRef(null); 13 14 const handleCountryChange = (countryCode) => { 15 setSelectedCountry(countryCode); 16 setIsDropdownOpen(false); 17 }; 18 19 // Close dropdown when clicking outside 20 useEffect(() => { 21 function handleClickOutside(event) { 22 if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { 23 setIsDropdownOpen(false); 24 } 25 } 26 27 document.addEventListener('mousedown', handleClickOutside); 28 return () => { 29 document.removeEventListener('mousedown', handleClickOutside); 30 }; 31 }, []); 32 33 // Scroll to selected country when dropdown opens 34 useEffect(() => { 35 if (isDropdownOpen && selectedCountry && selectedItemRef.current) { 36 // Small delay to ensure dropdown is fully rendered 37 setTimeout(() => { 38 selectedItemRef.current.scrollIntoView({ 39 behavior: 'auto', 40 block: 'center' 41 }); 42 }, 100); 43 } 44 }, [isDropdownOpen, selectedCountry]); 45 46 // Find selected country data 47 const selectedCountryData = countries.find(country => country.code === selectedCountry); 48 49 // Filter countries based on search term 50 const filteredCountries = searchTerm && enableSearch 51 ? countries.filter(country => 52 country.name.toLowerCase().includes(searchTerm.toLowerCase())) 53 : countries; 54 55 // Function to assign ref to selected country list item 56 const getItemRef = (code) => { 57 if (code === selectedCountry) { 58 return selectedItemRef; 59 } 60 return null; 61 }; 62 63 return ( 64 <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8"> 65 <div className="max-w-md mx-auto bg-white rounded-xl shadow-md md:max-w-2xl p-6"> 66 <h1 className="text-2xl font-bold text-gray-900 mb-6">Country Select Example</h1> 67 68 {/* Toggle for flag type */} 69 <div className="mb-6"> 70 <label className="inline-flex items-center cursor-pointer"> 71 <input 72 type="checkbox" 73 checked={useImageFlags} 74 onChange={() => setUseImageFlags(!useImageFlags)} 75 className="sr-only peer" 76 /> 77 <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div> 78 <span className="ms-3 text-sm font-medium text-gray-900"> 79 {useImageFlags ? 'Using Image Flags' : 'Using Emoji Flags'} 80 </span> 81 </label> 82 </div> 83 84 {/* Toggle for search functionality */} 85 <div className="mb-6"> 86 <label className="inline-flex items-center cursor-pointer"> 87 <input 88 type="checkbox" 89 checked={enableSearch} 90 onChange={() => setEnableSearch(!enableSearch)} 91 className="sr-only peer" 92 /> 93 <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div> 94 <span className="ms-3 text-sm font-medium text-gray-900"> 95 {enableSearch ? 'Search Enabled' : 'Search Disabled'} 96 </span> 97 </label> 98 </div> 99 100 {/* Country Select Dropdown */} 101 <div className="mb-6"> 102 <label htmlFor="country-select" className="block text-sm font-medium text-gray-700 mb-1"> 103 Select a Country 104 </label> 105 106 {useImageFlags ? ( 107 // Custom dropdown for image flags 108 <div className="relative" ref={dropdownRef}> 109 <button 110 type="button" 111 onClick={() => setIsDropdownOpen(!isDropdownOpen)} 112 className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2.5 border text-left" 113 > 114 {selectedCountry ? ( 115 <div className="flex items-center"> 116 <img 117 src={getFlagImageUrl(selectedCountry, 40)} 118 alt={selectedCountryData?.name} 119 className="h-5 w-auto mr-2" 120 /> 121 <span>{selectedCountryData?.name || 'Choose a country...'}</span> 122 </div> 123 ) : ( 124 <span>Choose a country...</span> 125 )} 126 </button> 127 128 {isDropdownOpen && ( 129 <div className="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto"> 130 {enableSearch && ( 131 <div className="sticky top-0 bg-white p-2 border-b border-gray-200"> 132 <input 133 type="text" 134 placeholder="Search countries..." 135 value={searchTerm} 136 onChange={(e) => setSearchTerm(e.target.value)} 137 className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 138 onClick={(e) => e.stopPropagation()} 139 /> 140 </div> 141 )} 142 <ul className="py-1"> 143 {filteredCountries.length > 0 ? ( 144 filteredCountries.map(({ code, name }) => ( 145 <li 146 key={code} 147 onClick={() => handleCountryChange(code)} 148 className={`flex items-center px-3 py-2 hover:bg-gray-100 cursor-pointer ${ 149 code === selectedCountry 150 ? 'bg-blue-50 animate-[pulse_1.5s_ease-in-out]' 151 : '' 152 }`} 153 ref={getItemRef(code)} 154 > 155 <img 156 src={getFlagImageUrl(code, 40)} 157 alt={name} 158 className="h-5 w-8 object-cover mr-2" 159 /> 160 <span>{name}</span> 161 </li> 162 )) 163 ) : ( 164 <li className="px-3 py-2 text-gray-500">No countries found</li> 165 )} 166 </ul> 167 </div> 168 )} 169 </div> 170 ) : ( 171 // Regular dropdown with emoji flags 172 <div className="relative" ref={dropdownRef}> 173 {enableSearch ? ( 174 <div className="relative"> 175 <button 176 type="button" 177 onClick={() => setIsDropdownOpen(!isDropdownOpen)} 178 className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2.5 border text-left" 179 > 180 {selectedCountry ? ( 181 <div className="flex items-center"> 182 <span className="mr-2">{getFlagEmoji(selectedCountry)}</span> 183 <span>{selectedCountryData?.name || 'Choose a country...'}</span> 184 </div> 185 ) : ( 186 <span>Choose a country...</span> 187 )} 188 </button> 189 190 {isDropdownOpen && ( 191 <div className="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto"> 192 <div className="sticky top-0 bg-white p-2 border-b border-gray-200"> 193 <input 194 type="text" 195 placeholder="Search countries..." 196 value={searchTerm} 197 onChange={(e) => setSearchTerm(e.target.value)} 198 className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 199 onClick={(e) => e.stopPropagation()} 200 /> 201 </div> 202 <ul className="py-1"> 203 {filteredCountries.length > 0 ? ( 204 filteredCountries.map(({ code, name }) => ( 205 <li 206 key={code} 207 onClick={() => handleCountryChange(code)} 208 className={`flex items-center px-3 py-2 hover:bg-gray-100 cursor-pointer ${code === selectedCountry ? 'bg-blue-50' : ''}`} 209 ref={getItemRef(code)} 210 > 211 <span className="mr-2 inline-block w-8 text-center">{getFlagEmoji(code)}</span> 212 <span>{name}</span> 213 </li> 214 )) 215 ) : ( 216 <li className="px-3 py-2 text-gray-500">No countries found</li> 217 )} 218 </ul> 219 </div> 220 )} 221 </div> 222 ) : ( 223 <select 224 id="country-select" 225 value={selectedCountry} 226 onChange={(e) => handleCountryChange(e.target.value)} 227 className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2.5 border" 228 > 229 <option value="">Choose a country...</option> 230 {countries.map(({ code, name }) => ( 231 <option key={code} value={code}> 232 {getFlagEmoji(code)} {name} 233 </option> 234 ))} 235 </select> 236 )} 237 </div> 238 )} 239 </div> 240 241 {/* Selected Country Display */} 242 {selectedCountryData && ( 243 <div className="mt-6 p-4 border border-gray-200 rounded-lg bg-gray-50"> 244 <h2 className="text-lg font-medium text-gray-900 mb-2">Selected Country</h2> 245 <div className="flex items-center space-x-3"> 246 {useImageFlags ? ( 247 <img 248 src={getFlagImageUrl(selectedCountryData.code, 40)} 249 alt={selectedCountryData.code} 250 className="w-12 h-auto" 251 /> 252 ) : ( 253 <span className="text-4xl">{getFlagEmoji(selectedCountryData.code)}</span> 254 )} 255 <div> 256 <p className="font-medium text-gray-800">{selectedCountryData.name}</p> 257 <p className="text-sm text-gray-500">Code: {selectedCountryData.code}</p> 258 </div> 259 </div> 260 </div> 261 )} 262 </div> 263 </div> 264 ); 265}
Click below to watch the React component in action:
https://github.com/user-attachments/assets/3513980f-1669-4413-a5ce-df3c79db6ecb
The video demonstrates:
The Angular module provides functions to generate template code and full Angular components.
1const { angular, getAllCountries } = require('country-flags-util'); 2 3// Generate Angular template code 4const templateCode = angular.getAngularCountrySelect(getAllCountries(), { 5 id: 'angular-country-select', 6 ngModel: 'selectedCountry', 7 useImageFlags: true, 8 flagWidth: 25 9}); 10 11// Generate a complete Angular component with module 12const { component, module, usage } = angular.getAngularCountryComponent(true);
The Vanilla JS module provides functions to generate JavaScript code for plain web applications.
1const { vanilla } = require('country-flags-util'); 2 3// Generate vanilla JS code 4const jsCode = vanilla.getVanillaJsCode({ 5 containerId: 'country-container', 6 selectId: 'vanilla-country-select', 7 selectClass: 'form-select', 8 selectedCode: 'AU', 9 useImageFlags: true, 10 flagWidth: 30 11}); 12 13// Generate complete HTML & JS implementation 14const { html, js } = vanilla.getVanillaImplementation({ 15 containerId: 'country-container', 16 selectId: 'country-select' 17});
1// Using the generated component 2import React, { useState, useRef, useEffect } from 'react'; 3import { getAllCountries, getFlagImageUrl, getFlagEmoji } from 'country-flags-util'; 4 5export default function CountrySelectPage() { 6 const [selectedCountry, setSelectedCountry] = useState(''); 7 const [useImageFlags, setUseImageFlags] = useState(true); 8 const [enableSearch, setEnableSearch] = useState(true); 9 const [isDropdownOpen, setIsDropdownOpen] = useState(false); 10 const [searchTerm, setSearchTerm] = useState(''); 11 const countries = getAllCountries(); 12 const dropdownRef = useRef(null); 13 const selectedItemRef = useRef(null); 14 15 const handleCountryChange = (countryCode) => { 16 setSelectedCountry(countryCode); 17 setIsDropdownOpen(false); 18 }; 19 20 // Close dropdown when clicking outside 21 useEffect(() => { 22 function handleClickOutside(event) { 23 if (dropdownRef.current && !dropdownRef.current.contains(event.target)) { 24 setIsDropdownOpen(false); 25 } 26 } 27 28 document.addEventListener('mousedown', handleClickOutside); 29 return () => { 30 document.removeEventListener('mousedown', handleClickOutside); 31 }; 32 }, []); 33 34 // Scroll to selected country when dropdown opens 35 useEffect(() => { 36 if (isDropdownOpen && selectedCountry && selectedItemRef.current) { 37 // Small delay to ensure dropdown is fully rendered 38 setTimeout(() => { 39 selectedItemRef.current.scrollIntoView({ 40 behavior: 'auto', 41 block: 'center' 42 }); 43 }, 100); 44 } 45 }, [isDropdownOpen, selectedCountry]); 46 47 // Find selected country data 48 const selectedCountryData = countries.find(country => country.code === selectedCountry); 49 50 // Filter countries based on search term 51 const filteredCountries = searchTerm && enableSearch 52 ? countries.filter(country => 53 country.name.toLowerCase().includes(searchTerm.toLowerCase())) 54 : countries; 55 56 // Function to assign ref to selected country list item 57 const getItemRef = (code) => { 58 if (code === selectedCountry) { 59 return selectedItemRef; 60 } 61 return null; 62 }; 63 64 return ( 65 <div className="min-h-screen bg-gray-50 py-12 px-4 sm:px-6 lg:px-8"> 66 <div className="max-w-md mx-auto bg-white rounded-xl shadow-md md:max-w-2xl p-6"> 67 <h1 className="text-2xl font-bold text-gray-900 mb-6">Country Select Example</h1> 68 69 {/* Toggle for flag type */} 70 <div className="mb-6"> 71 <label className="inline-flex items-center cursor-pointer"> 72 <input 73 type="checkbox" 74 checked={useImageFlags} 75 onChange={() => setUseImageFlags(!useImageFlags)} 76 className="sr-only peer" 77 /> 78 <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div> 79 <span className="ms-3 text-sm font-medium text-gray-900"> 80 {useImageFlags ? 'Using Image Flags' : 'Using Emoji Flags'} 81 </span> 82 </label> 83 </div> 84 85 {/* Toggle for search functionality */} 86 <div className="mb-6"> 87 <label className="inline-flex items-center cursor-pointer"> 88 <input 89 type="checkbox" 90 checked={enableSearch} 91 onChange={() => setEnableSearch(!enableSearch)} 92 className="sr-only peer" 93 /> 94 <div className="relative w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div> 95 <span className="ms-3 text-sm font-medium text-gray-900"> 96 {enableSearch ? 'Search Enabled' : 'Search Disabled'} 97 </span> 98 </label> 99 </div> 100 101 {/* Country Select Dropdown */} 102 <div className="mb-6"> 103 <label htmlFor="country-select" className="block text-sm font-medium text-gray-700 mb-1"> 104 Select a Country 105 </label> 106 107 {useImageFlags ? ( 108 // Custom dropdown for image flags 109 <div className="relative" ref={dropdownRef}> 110 <button 111 type="button" 112 onClick={() => setIsDropdownOpen(!isDropdownOpen)} 113 className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2.5 border text-left" 114 > 115 {selectedCountry ? ( 116 <div className="flex items-center"> 117 <img 118 src={getFlagImageUrl(selectedCountry, 40)} 119 alt={selectedCountryData?.name} 120 className="h-5 w-auto mr-2" 121 /> 122 <span>{selectedCountryData?.name || 'Choose a country...'}</span> 123 </div> 124 ) : ( 125 <span>Choose a country...</span> 126 )} 127 </button> 128 129 {isDropdownOpen && ( 130 <div className="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto"> 131 {enableSearch && ( 132 <div className="sticky top-0 bg-white p-2 border-b border-gray-200"> 133 <input 134 type="text" 135 placeholder="Search countries..." 136 value={searchTerm} 137 onChange={(e) => setSearchTerm(e.target.value)} 138 className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 139 onClick={(e) => e.stopPropagation()} 140 /> 141 </div> 142 )} 143 <ul className="py-1"> 144 {filteredCountries.length > 0 ? ( 145 filteredCountries.map(({ code, name }) => ( 146 <li 147 key={code} 148 onClick={() => handleCountryChange(code)} 149 className={`flex items-center px-3 py-2 hover:bg-gray-100 cursor-pointer ${ 150 code === selectedCountry 151 ? 'bg-blue-50 animate-[pulse_1.5s_ease-in-out]' 152 : '' 153 }`} 154 ref={getItemRef(code)} 155 > 156 <img 157 src={getFlagImageUrl(code, 40)} 158 alt={name} 159 className="h-5 w-8 object-cover mr-2" 160 /> 161 <span>{name}</span> 162 </li> 163 )) 164 ) : ( 165 <li className="px-3 py-2 text-gray-500">No countries found</li> 166 )} 167 </ul> 168 </div> 169 )} 170 </div> 171 ) : ( 172 // Regular dropdown with emoji flags 173 <div className="relative" ref={dropdownRef}> 174 {enableSearch ? ( 175 <div className="relative"> 176 <button 177 type="button" 178 onClick={() => setIsDropdownOpen(!isDropdownOpen)} 179 className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2.5 border text-left" 180 > 181 {selectedCountry ? ( 182 <div className="flex items-center"> 183 <span className="mr-2">{getFlagEmoji(selectedCountry)}</span> 184 <span>{selectedCountryData?.name || 'Choose a country...'}</span> 185 </div> 186 ) : ( 187 <span>Choose a country...</span> 188 )} 189 </button> 190 191 {isDropdownOpen && ( 192 <div className="absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-y-auto"> 193 <div className="sticky top-0 bg-white p-2 border-b border-gray-200"> 194 <input 195 type="text" 196 placeholder="Search countries..." 197 value={searchTerm} 198 onChange={(e) => setSearchTerm(e.target.value)} 199 className="w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500" 200 onClick={(e) => e.stopPropagation()} 201 /> 202 </div> 203 <ul className="py-1"> 204 {filteredCountries.length > 0 ? ( 205 filteredCountries.map(({ code, name }) => ( 206 <li 207 key={code} 208 onClick={() => handleCountryChange(code)} 209 className={`flex items-center px-3 py-2 hover:bg-gray-100 cursor-pointer ${code === selectedCountry ? 'bg-blue-50' : ''}`} 210 ref={getItemRef(code)} 211 > 212 <span className="mr-2 inline-block w-8 text-center">{getFlagEmoji(code)}</span> 213 <span>{name}</span> 214 </li> 215 )) 216 ) : ( 217 <li className="px-3 py-2 text-gray-500">No countries found</li> 218 )} 219 </ul> 220 </div> 221 )} 222 </div> 223 ) : ( 224 <select 225 id="country-select" 226 value={selectedCountry} 227 onChange={(e) => handleCountryChange(e.target.value)} 228 className="block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 sm:text-sm p-2.5 border" 229 > 230 <option value="">Choose a country...</option> 231 {countries.map(({ code, name }) => ( 232 <option key={code} value={code}> 233 {getFlagEmoji(code)} {name} 234 </option> 235 ))} 236 </select> 237 )} 238 </div> 239 )} 240 </div> 241 242 {/* Selected Country Display */} 243 {selectedCountryData && ( 244 <div className="mt-6 p-4 border border-gray-200 rounded-lg bg-gray-50"> 245 <h2 className="text-lg font-medium text-gray-900 mb-2">Selected Country</h2> 246 <div className="flex items-center space-x-3"> 247 {useImageFlags ? ( 248 <img 249 src={getFlagImageUrl(selectedCountryData.code, 40)} 250 alt={selectedCountryData.code} 251 className="w-12 h-auto" 252 /> 253 ) : ( 254 <span className="text-4xl">{getFlagEmoji(selectedCountryData.code)}</span> 255 )} 256 <div> 257 <p className="font-medium text-gray-800">{selectedCountryData.name}</p> 258 <p className="text-sm text-gray-500">Code: {selectedCountryData.code}</p> 259 </div> 260 </div> 261 </div> 262 )} 263 </div> 264 </div> 265 ); 266}
Click below to watch the React component in action:
The video demonstrates:
1// country.component.ts 2import { Component } from '@angular/core'; 3import { getAllCountries, getFlagImageUrl } from 'country-flags-util'; 4 5@Component({ 6 selector: 'app-country-selector', 7 template: ` 8 <select [(ngModel)]="selectedCountry" (ngModelChange)="onCountryChange($event)" class="form-control"> 9 <option *ngFor="let country of countries" [value]="country.code"> 10 <img [src]="getFlagUrl(country.code)" [alt]="country.name" style="width: 30px; margin-right: 5px;"> 11 {{ country.name }} 12 </option> 13 </select> 14 ` 15}) 16export class CountrySelectorComponent { 17 countries = getAllCountries(); 18 selectedCountry = 'US'; 19 20 getFlagUrl(code: string): string { 21 return getFlagImageUrl(code, 30); 22 } 23 24 onCountryChange(countryCode: string): void { 25 console.log('Selected country:', countryCode); 26 } 27}
1<!DOCTYPE html> 2<html lang="en"> 3<head> 4 <meta charset="UTF-8"> 5 <title>Country Selector Example</title> 6 <script src="node_modules/country-flags-util/index.js"></script> 7 <script> 8 document.addEventListener('DOMContentLoaded', function() { 9 const container = document.getElementById('country-container'); 10 const { getAllCountries, getFlagImageUrl } = countryFlagsUtil; 11 12 const countrySelect = document.createElement('select'); 13 countrySelect.id = 'country-select'; 14 countrySelect.className = 'form-select'; 15 16 getAllCountries().forEach(function(country) { 17 const option = document.createElement('option'); 18 option.value = country.code; 19 20 const flagImg = document.createElement('img'); 21 flagImg.src = getFlagImageUrl(country.code, 30); 22 flagImg.alt = country.code; 23 flagImg.style.width = '30px'; 24 flagImg.style.marginRight = '5px'; 25 flagImg.style.verticalAlign = 'middle'; 26 27 option.appendChild(flagImg); 28 option.appendChild(document.createTextNode(country.name)); 29 30 if(country.code === 'US') { 31 option.selected = true; 32 } 33 34 countrySelect.appendChild(option); 35 }); 36 37 countrySelect.addEventListener('change', function(e) { 38 console.log('Selected country:', e.target.value); 39 }); 40 41 container.appendChild(countrySelect); 42 }); 43 </script> 44</head> 45<body> 46 <h1>Country Selector</h1> 47 <div id="country-container"></div> 48</body> 49</html>
This library uses Unicode flag emojis which are supported in most modern browsers. Image flags using flagcdn.com are supported across all browsers.
Contributions are welcome! Please feel free to submit a Pull Request.
git checkout -b feature/amazing-feature
)git commit -m 'Add some amazing feature'
)git push origin feature/amazing-feature
)This project is licensed under the MIT License - see the LICENSE file for details.
Made with ❤️ by Nabarup Roy
No vulnerabilities found.
No security vulnerabilities found.