React Installation

Integrate Countries Cities AR with React using Vite or Create React App

Compatibility: React 16.8+ with hooks support

1. Create React App

npx create-react-app my-app --template typescript cd my-app

2. Install the package

npm install countries-cities-ar

3. Basic Component

Create a simple country selector component:

CountryPicker.tsx
import React, { useState } from 'react';
import { allCountries, type Country, type City } from 'countries-cities-ar';

export default function CountryPicker() {
  const [selectedCountry, setSelectedCountry] = useState<Country | null>(null);
  const [selectedCity, setSelectedCity] = useState<City | null>(null);

  const handleCountryChange = (code: string) => {
    const country = allCountries.find(c => c.code === code);
    setSelectedCountry(country || null);
    setSelectedCity(null);
  };

  return (
    <div className="flex flex-col gap-4">
      <select 
        onChange={(e) => handleCountryChange(e.target.value)}
        className="px-4 py-2 rounded border"
      >
        <option value="">Select Country</option>
        {allCountries.map(country => (
          <option key={country.code} value={country.code}>
            {country.nameAr} - {country.name}
          </option>
        ))}
      </select>

      {selectedCountry && selectedCountry.cities.length > 0 && (
        <select 
          onChange={(e) => {
            const city = selectedCountry.cities.find(c => c.name === e.target.value);
            setSelectedCity(city || null);
          }}
          className="px-4 py-2 rounded border"
        >
          <option value="">Select City</option>
          {selectedCountry.cities.map((city, idx) => (
            <option key={idx} value={city.name}>
              {city.nameAr} - {city.name}
            </option>
          ))}
        </select>
      )}

      {selectedCity && (
        <div className="p-4 bg-gray-100 rounded">
          <p>Selected: {selectedCity.nameAr}</p>
          <p>English: {selectedCity.name}</p>
        </div>
      )}
    </div>
  );
}

4. Use in App

App.tsx
import React from 'react';
import CountryPicker from './CountryPicker';

function App() {
  return (
    <div className="App">
      <h1>Select Your Location</h1>
      <CountryPicker />
    </div>
  );
}

export default App;

5. With Search

import { searchCountries } from 'countries-cities-ar';

const results = searchCountries('egy');
// Returns countries matching the search term

Next Steps

  • • Check the Examples section for more patterns
  • • Use TypeScript for better type safety
  • • Consider memoization for large lists

Countries Cities AR

Documentation

Version
v3.0.1
250 دولة • 4,642 محافظة