Add src/components/LanguageSwitcher.tsx
This commit is contained in:
63
src/components/LanguageSwitcher.tsx
Normal file
63
src/components/LanguageSwitcher.tsx
Normal file
@@ -0,0 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter, usePathname } from 'next/navigation';
|
||||
import { i18n, Locale } from '@/lib/i18nConfig';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select'; // Assuming shadcn-ui select component
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
// Placeholder for shadcn-ui select if not available:
|
||||
// Replace with your actual UI kit's Select/Dropdown or a simple <select> element.
|
||||
// If you don't have shadcn-ui, you might need to create these components or adjust imports.
|
||||
// For example, a basic HTML select:
|
||||
/*
|
||||
const BasicSelect = ({ value, onChange, options, placeholder }) => (
|
||||
<select value={value} onChange={(e) => onChange(e.target.value)}>
|
||||
{placeholder && <option value="" disabled>{placeholder}</option>}
|
||||
{options.map((option) => (
|
||||
<option key={option.value} value={option.value}>{option.label}</option>
|
||||
))}
|
||||
</select>
|
||||
);
|
||||
*/
|
||||
|
||||
interface LanguageSwitcherProps {
|
||||
currentLocale: Locale;
|
||||
}
|
||||
|
||||
export function LanguageSwitcher({ currentLocale }: LanguageSwitcherProps) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const [isMounted, setIsMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setIsMounted(true);
|
||||
}, []);
|
||||
|
||||
if (!isMounted) {
|
||||
return null; // Or a loading spinner
|
||||
}
|
||||
|
||||
const onSelectChange = (newLocale: Locale) => {
|
||||
// Replace the current locale in the pathname with the new one
|
||||
const newPath = `/${newLocale}${pathname.substring(3)}`; // Assuming /en, /fr, /es are 3 chars
|
||||
router.push(newPath);
|
||||
|
||||
// Set cookie for middleware to remember preferred locale
|
||||
document.cookie = `NEXT_LOCALE=${newLocale}; path=/; max-age=31536000;`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Select onValueChange={onSelectChange} defaultValue={currentLocale}>
|
||||
<SelectTrigger className="w-[100px] bg-background-accent text-foreground">
|
||||
<SelectValue placeholder="Language" />
|
||||
</SelectTrigger>
|
||||
<SelectContent className="bg-card text-foreground">
|
||||
{i18n.locales.map((locale) => (
|
||||
<SelectItem key={locale} value={locale}>
|
||||
{locale.toUpperCase()}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user