Jump to main content

Namespaces

Namespaces are a way to organize translation files, allowing us to separate them by functionality or by type of content.

By default, we have a namespace called translation for all our translations, which is in the file src/locales/es/translation.json.

src/locales/es/translation.json
{
"Hola Este es un ejemplo de traduccion base": "Hola Este es un ejemplo de traduccion base"
}
  • If we want to separate our translations by functionality, we can create a new namespace called messages.

    src/locales/es/messages.json
    {
    "Mensaje de ejemplo": "Mensaje de ejemplo"
    }
  • If we want to separate our translations by type of content, we can create a new namespace called pages.

    src/locales/es/pages.json
    {
    "Texto en la pagina": "Texto en la pagina"
    }

Configuration in our hook

In our translation hook, we pass the namespace parameter to use the one we want, but by default, we pass translation.

src/hooks/useTranslation.tsx
"use client";
import { useTypedTranslation } from 'translate-projects-nextjs/hooks';
import es from '@/locales/es/translation.json';

type Tylelang = typeof es

export const useTranslation = (ns: string = 'translation') => {
return useTypedTranslation<Tylelang>(ns)
}

Using namespaces

We can use namespaces in our component.

In this case, we are going to use the namespace messages.

src/App.tsx
import { useTranslation } from '@/hooks/useTranslation'; We import our hook.

function App() {
const { t } = useTranslation('messages'); //We use the namespace
return (
<div>
<header>
{t('Mensaje de ejemplo')}
</header>
</div>
);
}

export default App;

Another way to use the namespace is by passing it as a parameter in the useTranslation function.

src/App.tsx
import { useTranslation } from '@/hooks/useTranslation'; We import our hook.

function App() {
const { t } = useTranslation(); //We don't pass the namespace.
return (
<div>
<header>
{t('Mensaje de ejemplo',{ns: 'messages'})} //We pass the namespace.
</header>
</div>
);
}