🐶
Next.js

Next-i18next: Get Current Language

By Filip on 10/05/2024

Learn how to use the `useTranslation` hook from next-i18next to effortlessly retrieve the current language in your Next.js application.

Next-i18next: Get Current Language

Table of Contents

Introduction

This guide will help you get the current language in your Next.js app using the next-i18next library. First, install the necessary packages: next-i18next, react-i18next, and i18next. Then, create a configuration file (e.g., next-i18next.config.js) to define supported languages and settings. Next, wrap your application with the appWithTranslation higher-order component in your _app.js file. To access the current language, you have several options: use the useTranslation hook to get the i18next instance and its language property, use the withTranslation higher-order component to inject the t function and i18n instance as props, or access the router locale using the useRouter hook. Once you have the current language, you can use it for various purposes, such as conditionally rendering content, formatting dates and currencies, or loading language-specific resources. Remember to organize and load your translations, consider using a language switcher, and leverage the features of next-i18next and i18next for a complete internationalization solution.

Step-by-Step Guide

Here's how to retrieve the current language in your Next.js application using the next-i18next library:

1. Installation:

Start by installing the required packages:

npm install next-i18next react-i18next i18next

2. Configuration:

Create a configuration file for next-i18next. This file defines supported languages, default language, and other settings. For example, create a file named next-i18next.config.js in your project root with the following content:

module.exports = {
  i18n: {
    defaultLocale: 'en',
    locales: ['en', 'fr', 'es'],
  },
};

3. Wrapping your application:

Wrap your application with the appWithTranslation higher-order component provided by next-i18next. This ensures translation functionality is available throughout your app. In your _app.js file:

import { appWithTranslation } from 'next-i18next';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default appWithTranslation(MyApp);

4. Accessing the current language:

There are several ways to access the current language within your components:

a) Using the useTranslation hook:

This hook provides access to the i18next instance and translation functions. You can get the current language using i18next.language:

import { useTranslation } from 'next-i18next';

function MyComponent() {
  const { t, i18n } = useTranslation();
  const currentLanguage = i18n.language;

  // ...
}

b) Using the withTranslation higher-order component:

This HOC injects the t function and i18n instance as props to your component:

import { withTranslation } from 'next-i18next';

function MyComponent({ t, i18n }) {
  const currentLanguage = i18n.language;

  // ...
}

export default withTranslation('common')(MyComponent);

c) Accessing router locale:

Next.js provides access to the current locale through the router object. You can access it within your components using the useRouter hook:

import { useRouter } from 'next/router';

function MyComponent() {
  const router = useRouter();
  const currentLanguage = router.locale;

  // ...
}

5. Using the current language:

Once you have the current language, you can use it for various purposes, such as:

  • Conditionally rendering content:
{currentLanguage === 'en' && <p>This is English content.</p>}
{currentLanguage === 'fr' && <p>Ceci est du contenu français.</p>}
  • Formatting dates and currencies:
const formattedDate = new Date().toLocaleDateString(currentLanguage);
  • Loading language-specific resources:
import(`./locales/${currentLanguage}.json`).then((data) => {
  // ...
});

Remember:

  • Ensure your translations are properly organized and loaded.
  • Consider using a language switcher component to allow users to change the language.
  • Leverage the features of next-i18next and i18next for a comprehensive internationalization solution.

By following these steps, you can effectively retrieve and utilize the current language in your Next.js application, providing a localized experience for your users.

Code Example

This code snippet demonstrates how to get the current language in a Next.js component using the next-i18next library. It imports the useTranslation hook to access translation functions and the current language information. The example retrieves the language code and displays it along with a translated greeting.

This example demonstrates how to access the current language in a Next.js component using the useTranslation hook from next-i18next:

import React from 'react';
import { useTranslation } from 'next-i18next';

function MyComponent() {
  const { t, i18n } = useTranslation('common'); // Replace 'common' with your namespace

  const currentLanguage = i18n.language;

  return (
    <div>
      <h1>{t('hello')}</h1>
      <p>The current language is: {currentLanguage}</p>
    </div>
  );
}

export default MyComponent;

Explanation:

  1. Import Necessary Components: We import React and the useTranslation hook from next-i18next.
  2. Use the Hook: We call the useTranslation hook with the namespace where our translations are stored (replace 'common' with your actual namespace). This returns an object containing the t function for translating text and the i18n instance.
  3. Get Current Language: We access the language property of the i18n instance to retrieve the current language code (e.g., 'en', 'fr').
  4. Render Content: We use the t function to translate the 'hello' key from our translations and display it in a heading. We also display the current language code in a paragraph.

Additional Considerations:

  • Language Switcher: You can build a language switcher component that allows users to change the language and update the i18n instance accordingly.
  • Dynamic Content: Use the current language to conditionally render content, format dates/currencies, or load language-specific resources.
  • Translation Files: Ensure your translation files are properly structured and placed within the correct directory as per next-i18next configuration.

Remember: This is a basic example. You can adapt and extend it to fit your specific needs and application structure.

Additional Notes

  • Server-Side Rendering (SSR) and Static Site Generation (SSG): next-i18next seamlessly integrates with Next.js's SSR and SSG capabilities, ensuring that the correct language is loaded and displayed on the initial page load, even when JavaScript is disabled.
  • Language Detection: You can configure next-i18next to automatically detect the user's preferred language based on browser settings or other criteria. This enhances the user experience by presenting content in their preferred language without manual selection.
  • Namespace Usage: Organize your translations into namespaces to manage them effectively. This is particularly useful for larger projects with multiple components or sections requiring translations.
  • Pluralization and Formatting: i18next provides features for handling pluralization and formatting numbers, dates, and currencies according to the current language's rules.
  • Contextual Translations: Use context to provide additional information for translations, ensuring accurate and appropriate rendering based on the specific usage.
  • Dynamic Language Switching: Implement a language switcher component that allows users to change the language on the fly. This can be achieved using Next.js routing or by updating the i18next instance directly.
  • SEO Considerations: Ensure that your translated content is discoverable by search engines. Use hreflang tags and other SEO best practices to optimize your multilingual website.
  • Performance Optimization: For large-scale applications, consider using techniques like code splitting and lazy loading to optimize the loading of translation files and improve performance.
  • Testing: Thoroughly test your internationalization implementation to ensure that translations are accurate, complete, and displayed correctly in different languages and contexts.

By carefully considering these additional notes and leveraging the full potential of next-i18next, you can create a robust and user-friendly multilingual Next.js application that caters to a global audience.

Summary

Step Action Description
1 Installation Install next-i18next, react-i18next, and i18next packages.
2 Configuration Create next-i18next.config.js to define supported languages and default language.
3 Wrap Application Use appWithTranslation HOC in _app.js to enable translations.
4 Access Current Language
- useTranslation Hook Access i18next.language within components.
- withTranslation HOC Inject i18n instance as a prop.
- Router Locale Use useRouter hook to access router.locale.
5 Utilize Current Language
- Conditional Rendering Display content based on language.
- Formatting Format dates and currencies according to locale.
- Resource Loading Load language-specific resources.

Conclusion

In conclusion, implementing internationalization in your Next.js application using next-i18next is a straightforward process that involves installation, configuration, wrapping your application, and accessing the current language. By following the steps outlined in this guide, you can effectively provide a localized experience for your users, enhancing their engagement and satisfaction. Remember to consider additional factors such as language detection, namespace usage, pluralization, formatting, contextual translations, dynamic language switching, SEO, performance optimization, and testing to ensure a comprehensive and robust internationalization solution. With careful planning and implementation, you can create a Next.js application that caters to a global audience and expands your reach.

References

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait