Reputation: 81
I want to get locale from component without using 'use client'. Is it possible with nextjs 13 with app router?
import en from '@/public/locales/en.json';
import ru from '@/public/locales/ru.json';
const Header = () => {
const router = useRouter();
const {locale} = router;
const t = locale === 'en' ? en : ru;
return <div>{t.title}</div>
}
const nextConfig = {
i18n: {
locales: ['en', 'ru']
}
}
It gives an error "useRouter only works in Client Components. Add the "use client" directive at the top of the file to use it". 'use client' solve this. How to get locale code, example 'en' to get locale from local file?
Upvotes: 0
Views: 8082
Reputation: 352
import { getLocale } from "next-intl/server";
export default async function Home() {
const locale = await getLocale();
return (
<main>
<div>{locale}</div>
</main>
);
}
you need to put await cause getLocale return promise value and make sure the component
Upvotes: 0
Reputation: 48
If anyone still need it, you can use {useLocale} from "next-intl"
and use it inside your server component.
import { useLocale } from "next-intl/server";
export default function ServerComponent() {
const locale = useLocale()
return (
<div>{locale}</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Upvotes: 0
Reputation: 1521
you can import getLocale
from "next-intl/server"
and use it inside your server component
import { getLocale } from "next-intl/server";
export default function Home() {
const locale = getLocale();
return (
<main>
<div>{locale}</div>
</main>
);
}
Upvotes: 1