I’m currently developing a Next.js 14 project that employs the app router along with the next-intl library.
My objective is to facilitate translations for the toast, form, and validation namespaces within the registration-form component. Ideally, I aim to retrieve messages passed down from the parent (via NextIntlContext) in page.tsx, merge them with picked messages, and then pass them along to RegistrationForm.
- useTranslations cannot be called without an argument
- getMessages function returns all available translations, not just those provided by parent
- I don’t want to provide all translation namespaces to registration-form component, just the ones it needs
My specific use-case is being able to call my custom useToast hook uses useTranslations hook.
src/hooks/useToast.ts
import { toast } from "sonner";
export function useToast() {
const t = useTranslations();
const toastError = (message: string) => {
toast.error(t("toast.error"), { description: message });
};
return {
toastError,
};
}
src/app/[locale]/layout.tsx
export default function Layout({children}: { children: React.ReactNode }) {
const messages = useMessages()
const toastMessages = {
toast: messages.toast as AbstractIntlMessages
}
return (
<body>
<NextIntlClientProvider messages={toastMessages}>
<MyToaster/>
{children}
</NextIntlClientProvider>
</body>
);
}
src/app/[locale]/page.tsx
export default function Registration() {
const messages = useMessages()
const pickedMessages = {
form: {
registration: (messages["form"] as AbstractIntlMessages)["registration"] as AbstractIntlMessages
},
validation: messages.validation as AbstractIntlMessages,
// ...parentMessages
}
return (
<main>
<NextIntlClientProvider messages={pickedMessages}>
<RegistrationForm/>
</NextIntlClientProvider>
</main>
);
}
src/components/form/registration-form.tsx
"use client";
const RegistrationForm = () => {
const t = useTranslations();
toastError(t("form.error"))
return (...);
};
export default RegistrationForm;
weather forecast is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.