lhoist-stay-safe/src/components/CountrySelect.jsx

46 lines
1.5 KiB
JavaScript

import { useState } from "react";
import { v4 as uuidv4 } from "uuid";
import { useWordpressCustomData } from "../hooks/WordpressFetchData.js";
import { useUserContext } from "../hooks/useUserContext.jsx";
export default function CountrySelect() {
const availableCountries = useWordpressCustomData("/available-countries");
const { country, changeCountry } = useUserContext();
const [isSubmenuOpen, setIsSubmenuOpen] = useState(false);
if (!availableCountries || !country) return <div className='country-select'>Loading...</div>;
function handleChangeCountry(key, value) {
changeCountry({ name: value, iso: key });
handleShowHideSubmenu();
}
function handleShowHideSubmenu() {
setIsSubmenuOpen(!isSubmenuOpen);
}
const countryOptions = Object.keys(availableCountries).map((key, value) => (
<li
key={uuidv4()}
className='country-select__option'
onClick={() => handleChangeCountry(key, availableCountries[key])}>
<img className='flag' src={`https://flagsapi.com/${key}/flat/32.png`} alt='' />
{availableCountries[key]}
</li>
));
if (!countryOptions) return;
return (
<div className='country-select'>
<button className='country-select__toggle' onClick={handleShowHideSubmenu}>
<img className='flag' src={`https://flagsapi.com/${country.iso}/flat/32.png`} alt='' />
{country.name}
</button>
<ul className='country-select__country-list' aria-hidden={!isSubmenuOpen}>
{countryOptions}
</ul>
</div>
);
}