umami/components/common/LanguageButton.js

44 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-09-07 10:22:16 +02:00
import React, { useState, useRef } from 'react';
import Globe from 'assets/globe.svg';
import useDocumentClick from 'hooks/useDocumentClick';
import Menu from './Menu';
import Button from './Button';
2020-09-08 04:48:40 +02:00
import { menuOptions } from 'lib/lang';
import styles from './LanguageButton.module.css';
2020-09-09 05:46:31 +02:00
import useLocale from '../../hooks/useLocale';
2020-09-07 10:22:16 +02:00
2020-09-08 00:25:09 +02:00
export default function LanguageButton({ menuPosition = 'bottom', menuAlign = 'left' }) {
2020-09-07 10:22:16 +02:00
const [showMenu, setShowMenu] = useState(false);
2020-09-09 05:46:31 +02:00
const [locale, setLocale] = useLocale();
2020-09-07 10:22:16 +02:00
const ref = useRef();
2020-09-08 04:48:40 +02:00
const selectedLocale = menuOptions.find(e => e.value === locale)?.display;
2020-09-07 10:22:16 +02:00
function handleSelect(value) {
2020-09-09 05:46:31 +02:00
setLocale(value);
2020-09-07 10:22:16 +02:00
window.localStorage.setItem('locale', value);
setShowMenu(false);
}
useDocumentClick(e => {
if (!ref.current.contains(e.target)) {
setShowMenu(false);
}
});
return (
<div ref={ref} className={styles.container}>
<Button icon={<Globe />} onClick={() => setShowMenu(true)} size="small">
2020-09-08 04:48:40 +02:00
<div className={locale}>{selectedLocale}</div>
2020-09-07 10:22:16 +02:00
</Button>
2020-09-08 00:25:09 +02:00
{showMenu && (
<Menu
options={menuOptions}
onSelect={handleSelect}
float={menuPosition}
align={menuAlign}
/>
)}
2020-09-07 10:22:16 +02:00
</div>
);
}