Internationalization for client side components #57405
-
I am using nextjs version 13.5.6 and using app router Internationalization for translating my components, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
did you added "use client" in files where is client side code? |
Beta Was this translation helpful? Give feedback.
-
After adding the import statement import If you need to access the dictionary from a client component, you should call the server-only function For example: // app/[lang]/layout.tsx
export default async function RootLayout({
children,
params,
}: {
children: React.ReactNode
params: { lang: Locale }
}) {
const dictionary = await getDictionary(params.lang)
return (
<html lang={params.lang}>
<body>
<DictionaryProvider dictionary={dictionary}>
{children}
</DictionaryProvider>
</body>
</html>
)
} // dictionary-provider.tsx
'use client'
type Dictionary = Awaited<ReturnType<typeof getDictionary>>
const DictionaryContext = React.createContext<Dictionary | null>(null)
export default function DictionaryProvider({
dictionary,
children,
}: {
dictionary: Dictionary
children: React.ReactNode
}) {
return (
<DictionaryContext.Provider value={dictionary}>
{children}
</DictionaryContext.Provider>
)
}
export function useDictionary() {
const dictionary = React.useContext(DictionaryContext)
if (dictionary === null) {
throw new Error('useDictionary hook must be used within DictionaryProvider')
}
return dictionary
} 'use client'
export default function YourClientComponent(){
const dictionary = useDictionary()
return <div>{dictionary.something}</div>
} |
Beta Was this translation helpful? Give feedback.
After adding the import statement import
'server-only'
in thelib/dictionary.ts
file, all the code in that file is now designated as server-only code and cannot be imported from a client component.If you need to access the dictionary from a client component, you should call the server-only function
getDictionary
in thelayout.tsx
(server component) file and then pass its result to a provider.For example: