JSPM

react-state-city-area-pincode-package

1.0.1
    • ESM via JSPM
    • ES Module Entrypoint
    • Export Map
    • Keywords
    • License
    • Repository URL
    • TypeScript Types
    • README
    • Created
    • Published
    • Downloads 13
    • Score
      100M100P100Q41104F
    • License MIT

    A React component package for Indian State, City, Area, and Pincode selection, extending react-country-state-city.

    Package Exports

    • react-state-city-area-pincode-package
    • react-state-city-area-pincode-package/dist/index.cjs.js
    • react-state-city-area-pincode-package/dist/index.esm.js

    This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-state-city-area-pincode-package) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

    Readme

    react-state-city-area-pincode-selector A React component package designed for streamlined selection of Indian States, Cities, Areas, and automatically populating Pincodes. This package builds upon react-country-state-city to extend location selection down to the area and pincode level, specifically tailored for Indian regions with a flexible data structure.

    Features India Default: Pre-configured to work primarily with Indian states, cities, areas, and pincodes, removing the need for a country selector.

    Area Selection: A custom AreaSelect component to list areas within a selected city, state, and country.

    Automatic Pincode Population: Automatically selects and displays the first associated pincode upon area selection.

    Flexible Pincode Data: Supports pincodes as either a single number/string or an array of numbers/strings in your custom data.

    Built-in Data Helpers: Utility functions to easily fetch area and pincode data.

    Tailwind CSS Ready: Components are designed to be styled easily with Tailwind CSS utility classes.

    Installation This package is intended to be published to npm. Once published, you can install it like any other npm package.

    npm install react-state-city-area-pincode-selector react-country-state-city

    or

    yarn add react-state-city-area-pincode-selector react-country-state-city

    Important: This package requires react and react-dom as peerDependencies. Ensure they are installed in your project. It also uses react-country-state-city as a peer dependency, so make sure to install it alongside this package.

    Basic Usage After installation, you can integrate the components into your React or Next.js application.

    // components/LocationSelector.jsx or app/page.tsx (if using App Router) 'use client'; // Required for client-side components in Next.js App Router

    import React, { useState } from 'react'; import { StateSelect, CitySelect, } from 'react-country-state-city'; import 'react-country-state-city/dist/react-country-state-city.css'; // Don't forget the CSS for react-country-state-city import { AreaSelect, PincodeSelect } from 'react-state-city-area-pincode-selector';

    export default function LocationSelector() { const [selectedState, setSelectedState] = useState(null); const [selectedCity, setSelectedCity] = useState(null); const [selectedArea, setSelectedArea] = useState(null); // Will hold the { id, name, pincodes[] } object const [selectedPincode, setSelectedPincode] = useState(null); // Will hold the auto-selected pincode string

    // Hardcode India's ID and ISO2 code as this selector defaults to India const INDIA_COUNTRY_ID = 101; const INDIA_COUNTRY_ISO2 = 'IN';

    // Handler for AreaSelect component's change event const handleAreaChange = (area) => { setSelectedArea(area); // Automatically select the first pincode if available if (area && area.pincodes && area.pincodes.length > 0) { setSelectedPincode(area.pincodes[0]); } else { setSelectedPincode(null); // Clear pincode if no area or no pincodes } };

    return (

    Location Selector

      <div className="bg-white p-8 rounded-lg shadow-xl w-full max-w-md">
        {/* State Selection */}
        <div className="mb-4">
          <label className="block text-gray-700 text-sm font-bold mb-2">
            Select State:
          </label>
          <StateSelect
            countryid={INDIA_COUNTRY_ID}
            onChange={(state) => {
              setSelectedState(state);
              setSelectedCity(null); // Reset downstream selectors
              setSelectedArea(null);
              setSelectedPincode(null);
            }}
            placeHolder="Select State"
            value={selectedState}
            className="w-full p-2 border rounded-md"
          />
        </div>
    
        {/* City Selection (visible if state is selected) */}
        {selectedState && (
          <div className="mb-4">
            <label className="block text-gray-700 text-sm font-bold mb-2">
              Select City:
            </label>
            <CitySelect
              countryid={INDIA_COUNTRY_ID}
              stateid={selectedState.id}
              onChange={(city) => {
                setSelectedCity(city);
                setSelectedArea(null); // Reset downstream selectors
                setSelectedPincode(null);
              }}
              placeHolder="Select City"
              value={selectedCity}
              className="w-full p-2 border rounded-md"
            />
          </div>
        )}
    
        {/* Area Selection (visible if city is selected) */}
        {selectedCity && (
          <div className="mb-4">
            <label className="block text-gray-700 text-sm font-bold mb-2">
              Select Area:
            </label>
            <AreaSelect
              countryCode={INDIA_COUNTRY_ISO2}
              stateCode={selectedState ? selectedState.state_code : ''} // Use state_code from react-country-state-city
              cityName={selectedCity.name}
              onChange={handleAreaChange} // Custom handler for Area selection
              placeHolder="Select Area"
              className="w-full p-2 border rounded-md"
            />
          </div>
        )}
    
        {/* Pincode Display (visible if area is selected) */}
        {selectedArea && (
          <div className="mb-4">
            <label className="block text-gray-700 text-sm font-bold mb-2">
              Pincode (Auto-Selected):
            </label>
            <PincodeSelect
              countryCode={INDIA_COUNTRY_ISO2}
              stateCode={selectedState ? selectedState.state_code : ''}
              cityName={selectedCity.name}
              areaName={selectedArea.name}
              selectedPincode={selectedPincode}
              placeHolder="Available Pincodes for Area"
              className="w-full"
            />
          </div>
        )}
    
        {/* Display Current Selection */}
        {(selectedState || selectedCity || selectedArea || selectedPincode) && (
          <div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-md">
            <h3 className="text-lg font-semibold text-blue-800 mb-2">Current Selection:</h3>
            <p className="text-blue-700">
              Country: India (IN)
              {selectedState && ` | State: ${selectedState.name} (${selectedState.state_code})`}
              {selectedCity && ` | City: ${selectedCity.name}`}
              {selectedArea && ` | Area: ${selectedArea.name}`}
              {selectedPincode && ` | Pincode: ${selectedPincode}`}
            </p>
          </div>
        )}
      </div>
    </div>

    ); }

    Advanced Usage

    1. Customizing Location Data (src/data/areas.json) The package includes sample data, but its true power comes from using your own, extensive location data.

    Location: The areas.json file is located at node_modules/react-state-city-area-pincode-selector/src/data/areas.json (after npm install).

    Structure: It should be an array of objects, where each object represents a city and its associated areas.

    [ { "countryCode": "IN", "stateCode": "GJ", "cityName": "Surat", "areas": [ { "id": "adajan", "name": "Adajan", "pincodes": ["395009", "395010"] }, { "id": "pal", "name": "Pal", "pincodes": 395009 }, { "id": "piplod", "name": "Piplod", "pincodes": ["395007"] } // ... add all your 600-700 Surat areas here ] }, { "countryCode": "IN", "stateCode": "MH", "cityName": "Mumbai", "areas": [ { "id": "andheri", "name": "Andheri", "pincodes": ["400053", "400058"] } ] } ]

    Pincode Flexibility:

    The pincodes property within an area object can be either:

    A single number or string (e.g., "pincodes": 395009 or "pincodes": "395009").

    An array of numbers or strings (e.g., "pincodes": ["395009", "395010"]).

    The package's internal data helpers (src/utils/data-helpers.js) will automatically normalize single pincodes into an array of strings (e.g., 395009 becomes ["395009"]) before passing them to components. This ensures consistency for handling pincode data.

    How to Update Your areas.json (Post-Publishing):

    Since areas.json is bundled with the package, if you update it directly in node_modules, those changes won't persist across npm install runs or be available to others.

    Modify in your package's source: Make changes to react-state-city-area-pincode-package/src/data/areas.json in your local development environment.

    Rebuild your package:

    cd react-state-city-area-pincode-package/ npm run build

    Increment version in package.json: Update the version field in react-state-city-area-pincode-package/package.json (e.g., from 1.0.0 to 1.0.1).

    Publish new version to npm:

    npm publish --access public

    Update in your Next.js app:

    cd my-nextjs-location-app/ npm update react-state-city-area-pincode-selector

    or npm install react-state-city-area-pincode-selector@latest if you updated to a major version

    This will pull down the latest version of your package with the updated data.

    1. Component Props Reference AreaSelect Props Prop Name

    Type

    Description

    Required

    countryCode

    string

    The ISO2 code of the country (e.g., 'IN'). Hardcoded to 'IN' in the example.

    Yes

    stateCode

    string

    The state_code (ISO2 equivalent) of the selected state from react-country-state-city (e.g., 'GJ').

    Yes

    cityName

    string

    The exact name of the selected city (e.g., 'Surat').

    Yes

    onChange

    function

    Callback function when an area is selected. Receives the selectedArea object, which has id, name, and a pincodes array (e.g., { id: 'adajan', name: 'Adajan', pincodes: ['395009', '395010'] }). Returns null if placeholder is selected.

    Yes

    placeHolder

    string

    Optional text for the default dropdown option (default: 'Select Area').

    No

    className

    string

    Optional Tailwind CSS classes for custom styling.

    No

    PincodeSelect Props (Display Component) This component is now primarily for displaying the auto-selected pincode and available pincodes, not for user selection.

    Prop Name

    Type

    Description

    Required

    countryCode

    string

    The ISO2 code of the country (e.g., 'IN').

    Yes

    stateCode

    string

    The state_code (ISO2 equivalent) of the selected state (e.g., 'GJ').

    Yes

    cityName

    string

    The exact name of the selected city (e.g., 'Surat').

    Yes

    areaName

    string

    The exact name of the selected area (e.g., 'Adajan').

    Yes

    selectedPincode

    string

    The single pincode string that has been automatically selected and should be highlighted.

    No

    placeHolder

    string

    Optional text for the title above the pincode list (default: 'Available Pincodes').

    No

    className

    string

    Optional Tailwind CSS classes for custom styling.

    No

    1. Direct Usage of Data Helpers You can also import and use the data helper functions directly from the package if you need to access the location data outside the components.

    import { getAreasOfCity, getPincodesOfArea } from 'react-state-city-area-pincode-selector';

    // Example: Fetch all areas for Surat, Gujarat, India const suratAreas = getAreasOfCity('IN', 'GJ', 'Surat'); console.log(suratAreas); // Output: [{ id: 'adajan', name: 'Adajan', pincodes: ['395009', '395010'] }, ...]

    // Example: Get pincodes for a specific area const palPincodes = getPincodesOfArea('IN', 'GJ', 'Surat', 'Pal'); console.log(palPincodes); // Output: ['395009'] (even if original data was just 395009)

    1. Styling Customization The components use inline styles and Tailwind CSS classes.

    Override with className: You can pass your own Tailwind classes via the className prop to any of the components (StateSelect, CitySelect, AreaSelect, PincodeSelect) to customize their appearance.

    Global Styles: For more extensive customization or branding, you can define global CSS styles that target the HTML elements rendered by the components. Inspect the component output in your browser's developer tools to see the generated HTML structure and classes.

    Tailwind Configuration: Remember to update your project's tailwind.config.js (or .ts) to include your package's source files in the content array for Tailwind to scan and generate necessary utility classes.

    // tailwind.config.js (in your Next.js app) module.exports = { content: [ // ... existing paths './node_modules/react-state-city-area-pincode-selector/src/**/*.{js,jsx,ts,tsx}', // Add this line ], // ... };

    1. Troubleshooting / FAQ "Cannot read properties of null (reading 'useState')": This often indicates multiple React instances. Ensure react and react-dom are correctly configured as peerDependencies in your package's package.json and are not included in dependencies or devDependencies of the package itself.

    "Module not found: Can't resolve 'react-state-city-area-pincode-selector'":

    Verify your package name in package.json matches the import statement.

    Ensure you ran npm install in your Next.js app after adding the package dependency.

    If using npm link (not recommended for production), ensure the link was created correctly in both directions.

    "Pincodes are not appearing or causing errors":

    Double-check your areas.json structure. The pincodes key must exist for each area object, and its value should be a number, string, or an array of numbers/strings.

    Ensure you rebuilt your package (npm run build in package directory) and restarted your Next.js app (npm run dev in Next.js app directory) after modifying areas.json.

    Styling Issues:

    Confirm react-country-state-city/dist/react-country-state-city.css is imported in your root layout/component.

    Ensure your tailwind.config.js correctly includes the path to your package's source files.

    Check for conflicting CSS rules.

    By following these guidelines, you can effectively use and manage your react-state-city-area-pincode-selector package within your Next.js projects and beyond.