본문 바로가기
Next.js

Building language switcher for Next.js : step by step guide

by NewbieDeveloper 2024. 12. 1.

Introduction

Building a multi-language website is essential in today's globalized world. This guide will help you create a language switcher in Next.js using Tailwind CSS, enabling seamless internationalization (i18n) support. Whether you're creating a personal blog, an e-commerce site, or an enterprise app, this tutorial is tailored for developers looking to enhance their applications' accessibility and reach.

 

Next.js language switcher step by step guide

 


Table of Contents

  1. Setting Up the Project
  2. Installing Dependencies
  3. Creating the Language Switcher Component
  4. Handling Translations with next-i18next
  5. Styling the Switcher with Tailwind CSS
  6. Testing the Language Switcher
  7. Advanced Customizations

1. Setting Up the Project

To get started, create a new Next.js project and install Tailwind CSS:

npx create-next-app@latest language-switcher-demo
cd language-switcher-demo
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

Configure Tailwind CSS

Update the `tailwind.config.js` file:

module.exports = {
  content: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {},
  },
  plugins: [],
};

Add Tailwind to your CSS file in `styles/globals.css`:

@tailwind base;
@tailwind components;
@tailwind utilities;

Run the server to confirm Tailwind is properly set up:

npm run dev

2. Installing Dependencies

Install the required libraries for internationalization and localization:

npm install next-i18next react-i18next i18next

3. Creating the Language Switcher Component

Create a new component called `LanguageSwitcher.js` inside the `components` directory:

'use client';

import { usePathname, useSearchParams, useRouter } from 'next/navigation';
import { useEffect, useState } from 'react';

const LanguageSwitcher = () => {
  const [mounted, setMounted] = useState(false);
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    setMounted(true);
  }, []);

  const switchLanguage = (locale) => {
    const queryParams = new URLSearchParams(searchParams.toString());
    router.push(`/${locale}${pathname}?${queryParams}`);
  };

  if (!mounted) {
    return null; 
  }

  return (
    <div className="flex space-x-4">
      <button
        onClick={() => switchLanguage('en')}
        className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-700"
      >
        English
      </button>
      <button
        onClick={() => switchLanguage('fr')}
        className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-700"
      >
        French
      </button>
    </div>
  );
};

export default LanguageSwitcher;

4. Handling Translations with `next-i18next`

Setting Up `next-i18next.config.js`

In the root directory, create a file named `next-i18next.config.js`:

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

Adding Translation Files

Create a directory `public/locales` with subdirectories for each language:

public/
  locales/
    en/
      common.json
    fr/
      common.json

Example content for `common.json`:

`en/common.json`:

{
  "greeting": "Hello, welcome to our site!"
}

`fr/common.json`:

{
  "greeting": "Bonjour, bienvenue sur notre site!"
}

5. Styling the Switcher with Tailwind CSS

Update the `LanguageSwitcher.js` to enhance its design:

<div className="flex items-center justify-center space-x-4 bg-gray-100 p-4 rounded shadow-md">
  <button
    onClick={() => switchLanguage('en')}
    className="px-4 py-2 font-semibold text-white bg-blue-500 hover:bg-blue-700 rounded"
  >
    English
  </button>
  <button
    onClick={() => switchLanguage('fr')}
    className="px-4 py-2 font-semibold text-white bg-green-500 hover:bg-green-700 rounded"
  >
    French
  </button>
</div>

6. Testing the Language Switcher

Update the `pages/index.js` file to use the `LanguageSwitcher` and display localized content:

import LanguageSwitcher from '../components/LanguageSwitcher';
import { useTranslation } from 'next-i18next/serverSideTranslations';

export default function Home() {
  const { t } = useTranslation('common');

  return (
    <div className="container mx-auto mt-10">
      <LanguageSwitcher />
      <h1 className="mt-10 text-3xl font-bold">{t('greeting')}</h1>
    </div>
  );
}

export async function getStaticProps({ locale }) {
  return {
    props: {
      ...(await serverSideTranslations(locale, ['common'])),
    },
  };
}

7. Advanced Customizations

Adding Flags

Integrate the `react-world-flags` library for visual cues:

npm install react-world-flags

Update the switcher to include flags:

import Flag from 'react-world-flags';

<div className="flex items-center space-x-4">
  <button onClick={() => switchLanguage('en')}>
    <Flag code="GB" className="w-6 h-6" />
    English
  </button>
  <button onClick={() => switchLanguage('fr')}>
    <Flag code="FR" className="w-6 h-6" />
    French
  </button>
</div>

Conclusion

You've now created a fully functional language switcher in Next.js using Tailwind CSS. This setup ensures your application is accessible to a global audience while maintaining excellent performance and scalability.

Experiment with additional languages or styling options to refine the user experience! If you have any questions, feel free to leave them below. 🚀

댓글