location-sl
v1.0.2
Published
A React component for selecting locations in Sri Lanka. This component allows users to enter a district, view suggestions, and select an area from the suggested locations.
Downloads
2
Readme
Sri Lanka Location Selector
A React component for selecting locations in Sri Lanka. This component allows users to enter a district, view suggestions, and select an area from the suggested locations.
Installation
To use this component in your project, you need to install it via npm:
npm install srilanka-location
import React from 'react';
import { suggestLocations } from 'srilanka-location';
const LocationSelector = () => {
const [district, setDistrict] = React.useState('');
const [suggestions, setSuggestions] = React.useState([]);
const [selectedArea, setSelectedArea] = React.useState('');
const [areas, setAreas] = React.useState([]);
const updateLocationSuggestions = (district) => {
const suggestions = suggestLocations(district);
setSuggestions(suggestions);
};
const handleDistrictChange = (e) => {
const newDistrict = e.target.value;
setDistrict(newDistrict);
updateLocationSuggestions(newDistrict);
};
const handleSuggestionClick = (suggestion) => {
setDistrict(suggestion.district); // Set district from suggestion
setAreas(suggestion.areas); // Set areas from suggestion
setSuggestions([]); // Clear suggestions after selection
};
const handleAreaChange = (e) => {
setSelectedArea(e.target.value);
};
return (
<div className="">
<input
type="text"
value={district}
onChange={handleDistrictChange}
placeholder="Enter location"
className="border border-gray-300 p-2 rounded-lg w-1/2"
/>
<div className="flex flex-col gap-2">
{suggestions.map((suggestion, index) => (
<div
key={index}
className="border border-gray-300 p-2 rounded-lg cursor-pointer"
onClick={() => handleSuggestionClick(suggestion)}
>
{suggestion.district}
</div>
))}
</div>
{Array.isArray(areas) && areas.length > 0 ? (
<select value={selectedArea} onChange={handleAreaChange}>
{areas.map((area, areaIndex) => (
<option key={areaIndex} value={area}>
{area}
</option>
))}
</select>
) : (
<div>No areas available</div>
)}
</div>
);
};
export default LocationSelector;