empire-countries-react
v0.0.5
Published
Empire Countries React library TypeScript project
Readme
Empire Countries
A comprehensive TypeScript library for working with countries data including flags, dial codes, currencies, timezones, and more. Available in two packages:
empire-countries- Core library with no dependenciesempire-countries-react- React components built on top of the core library
📦 Packages
empire-countries
Core library with country data, utilities, and classes. No React dependencies.
empire-countries-react
React components including PhoneNumberInput and CountryInput with beautiful UI.
🚀 Installation
Core Library
npm install empire-countries
# or
yarn add empire-countries
# or
pnpm add empire-countriesReact Components
npm install empire-countries-react
# or
yarn add empire-countries-react
# or
pnpm add empire-countries-reactNote: empire-countries-react requires React 16.8+ as a peer dependency.
📖 Usage
Core Library (empire-countries)
Basic Usage
import { Countries, Country } from 'empire-countries';
// Get all countries
const allCountries = Countries.getAll();
// Get a specific country
const usa = Countries.getOne({ code: 'US' });
console.log(usa?.title); // "United States of America"
console.log(usa?.dialCode); // "+1"
console.log(usa?.flag); // Flag emoji/HTML
// Search countries
const results = Countries.search({ search: 'United' });
// Returns countries matching "United" in name, code, dial code, or continentUsing the Country Class
import { Country } from 'empire-countries';
// Create a country instance
const country = new Country('US'); // Default to US
// Get country information
const countryData = country.getCountry();
console.log(countryData?.title, countryData?.dialCode);
// Search and filter countries
country.setSearch('United');
const filtered = country.getAllCountries();
// Pagination
country.setPage(1).setLimit(10);
const paginated = country.getPaginateCountries();
console.log(paginated.data); // Array of countries
console.log(paginated.totalPages); // Total number of pagesFind User's Country
import { Country } from 'empire-countries';
const country = new Country(null, true); // true = auto-detect country
// Or manually detect
await country.setMyCountry();
const myCountry = country.getMyCountry();
const selectedCountry = country.getCountry();Pagination
import { Countries } from 'empire-countries';
const result = Countries.paginate({
page: 1,
limit: 10,
search: 'United',
sortBy: 'title',
sortOrder: 'asc',
baseUrl: '/api/countries',
});
console.log(result.data); // Array of countries
console.log(result.total); // Total count
console.log(result.totalPages); // Total pages
console.log(result.hasNextPage); // Boolean
console.log(result.links); // Pagination linksMinimal Data (Lighter Weight)
import { Countries } from 'empire-countries';
// Get minimal country data (fewer fields)
const minimalCountries = Countries.getAllMinimal();
// Search minimal data
const minimalResults = Countries.searchMinimal({ search: 'United' });
// Get one minimal country
const minimalUSA = Countries.getOneMinimal({ code: 'US' });React Components (empire-countries-react)
PhoneNumberInput Component
import React, { useState } from 'react';
import { PhoneNumberInput, PhoneProps } from 'empire-countries-react';
// Note: CSS modules are bundled with the components, no need to import separately
function App() {
const [phone, setPhone] = useState<PhoneProps>({ code: null, number: null });
return (
<PhoneNumberInput
phone={phone}
setPhone={setPhone}
label="Phone Number"
placeholder="Enter your phone number"
required="*"
/>
);
}CountryInput Component
import React, { useState } from 'react';
import { CountryInput, Country } from 'empire-countries-react';
// Note: CSS modules are bundled with the components, no need to import separately
function App() {
const [selectedCountry, setSelectedCountry] = useState<Partial<Country> | null>(null);
return (
<CountryInput
selectedCountry={selectedCountry}
setSelectedCountry={setSelectedCountry}
label="Country"
placeholder="Select a country"
required="*"
/>
);
}Complete Form Example
import React, { useState } from 'react';
import { PhoneNumberInput, CountryInput, PhoneProps, Country } from 'empire-countries-react';
// Note: CSS modules are bundled with the components
function ContactForm() {
const [phone, setPhone] = useState<PhoneProps>({ code: null, number: null });
const [country, setCountry] = useState<Partial<Country> | null>(null);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
console.log('Phone:', phone);
console.log('Country:', country);
// Submit your form data
};
return (
<form onSubmit={handleSubmit}>
<PhoneNumberInput phone={phone} setPhone={setPhone} label="Phone Number" required="*" />
<CountryInput selectedCountry={country} setSelectedCountry={setCountry} label="Country" required="*" />
<button type="submit">Submit</button>
</form>
);
}📚 API Reference
Core Library
Countries (Static Class)
getAll(options?)- Get all countriesgetAllMinimal(options?)- Get all countries (minimal data)getOne(options)- Get one country by code, id, timezone, or currencygetOneMinimal(options)- Get one country (minimal data)search(query)- Search countriessearchMinimal(query)- Search countries (minimal data)paginate(options)- Paginate countriespaginateMinimal(options)- Paginate countries (minimal data)findMyCountry()- Detect user's country via IP
Country (Instance Class)
constructor(code?, autoDetect?)- Create country instancesetMyCountry()- Detect and set user's countrysetSelectedCountry(country)- Set selected countrysetSelectedCountryCode(code)- Set by country codesetSearch(query)- Set search querygetAllCountries()- Get filtered countriesgetPaginateCountries()- Get paginated countriesgetCountry()- Get current selected countrygetMyCountry()- Get detected country data
React Components
PhoneNumberInput
Props:
phone?: PhoneProps- Phone state object{ code, number }setPhone?: (phone: PhoneProps) => void- Phone state settersetSelectedCountry?: (country: Country | null) => void- Optional country setterlabel?: string- Input label (default: "Phone number")placeholder?: string- Input placeholderrequired?: string | null- Required indicator text
CountryInput
Props:
selectedCountry?: Partial<Country> | null- Selected countrysetSelectedCountry?: (country: Partial<Country> | null) => void- Country setterlabel?: string- Input label (default: "Country")placeholder?: string- Input placeholderrequired?: string | null- Required indicator text
🎨 Styling
The React components come with built-in CSS that is bundled with Vite. You can import the CSS file:
import 'empire-countries-react/dist/react.css';Or if your bundler supports it, the CSS will be automatically included via the style field in package.json.
You can customize the styles by overriding CSS variables in your application:
:root {
--color-primary: rgba(147, 51, 234, 0.5);
}If you need to customize the component styles, you can override the CSS classes in your own stylesheet.
📝 TypeScript Support
Both packages are written in TypeScript and include full type definitions. All types are exported for your use:
import type { Country, CountryMinimal, CountryCode, PhoneProps, PaginationResult } from 'empire-countries';🌟 Features
- ✅ 200+ countries with complete data
- ✅ Country flags (emoji and HTML)
- ✅ Dial codes for phone numbers
- ✅ Currency information
- ✅ Timezone data
- ✅ Native names in multiple languages
- ✅ Search and filter functionality
- ✅ Pagination support
- ✅ Auto-detect user's country
- ✅ TypeScript support
- ✅ React components with beautiful UI
- ✅ Zero dependencies (core library)
- ✅ Lightweight minimal data option
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
📄 License
MIT
👤 Author
Syed Amir Ali
- GitHub: @SyedAmirAli
- LinkedIn: syedamirali473
🙏 Acknowledgments
Made with ❤️ by Syed Amir Ali
If you find this library useful, consider starring the repository or supporting the project!
