Next-translate

Author : JaNakh Pon , December 04, 2021

Tags

Intro

In this article, we are going to use next-dynamic-seo repo from the previous article and set up localization using next-translate in a few steps.

Summary

There are many packages out there for localization/internalization but I prefer to use next-translate over other because it really works well with getStaticProps and getServerSideProps.

Firstly, we will install next-translate package, then create locales folder and then we will create i18n.json and add nextTranslate to our next.config.js.

Setup

Let's start by installing next-translate into our repo:

> yarn add next-translate

And create locales folder:

> mkdir locales && cd locales && mkdir mm en

and then we will need to add json translation files under mm and en.

common.json
{
  "change-locale": "Change Localization",
  "title": "Hello",
  "withValue": "Today - {{date}}"
}

And we will also need to create i18n.json and add nextTranslate to our next.config.js:

i18n.json
{
  "locales": ["en", "mm"],
  "defaultLocale": "en",
  "pages": {
    "*": ["common"],
    "/about": ["common", "about"]
  }
}
next.config.js
const withPWA = require('next-pwa')
const nextTranslate = require('next-translate');
const withPlugins = require("next-compose-plugins");

module.exports = withPlugins([
  [nextTranslate()],
  [withPWA, {
    pwa: {
      dest: 'public',
    },
  }],
]);

Implementation

Now, we should be able to use nextTranslate in out pages and components:

index.tsx
import React, { useEffect, useState } from "react";
import type { NextPage } from "next";
import Page from "@layouts/page";
import styles from "@styles/Home.module.css";
import useTranslation from "next-translate/useTranslation";
import setLanguage from "next-translate/setLanguage";
import { useRouter } from "next/router";
import Link from "next/link";
import moment from "moment";
import "moment/locale/my";

const Home: NextPage = () => {
  const { t } = useTranslation("common");
  const router = useRouter();
  const [dval, setDval] = useState("");
  const withval = t("withValue", { date: dval });

  useEffect(() => {
    moment.locale(router.locale === "en" ? "en" : "my");
    setDval(moment().format("LL"));
  }, [router]);

  return (
    <Page
      meta={{
        title: "Dynamic",
        description: `Website's home page`,
      }}
    >
      <div className={styles.container}>
        <main className={styles.main}>
          <h1 className={styles.title}>{t("title")}</h1>
          <h2>{withval} </h2>
          <p className={styles.description}>
            <button
              onClick={() => setLanguage(router.locale === "en" ? "mm" : "en")}
            >
              {t("change-locale")}
            </button>
          </p>
          <Link href="/about" passHref>
            Go to About Page!
          </Link>
          <div className={styles.grid}>
            <a
              href="https://github.com/vercel/next.js/tree/master/examples"
              className={styles.card}
            >
              <h2>Examples &rarr;</h2>
              <p>Discover and deploy boilerplate example Next.js projects.</p>
            </a>

            <a
              href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
              className={styles.card}
            >
              <h2>Deploy &rarr;</h2>
              <p>
                Instantly deploy your Next.js site to a public URL with Vercel.
              </p>
            </a>
          </div>
        </main>
      </div>
    </Page>
  );
};

export default Home;

And about.tsx:

about.tsx
import type { NextPage } from "next";
import Page from "@layouts/page";
import useTranslation from "next-translate/useTranslation";

const About: NextPage = () => {
  const { t } = useTranslation("about");

  return (
    <Page
      meta={{
        title: "Dynamic",
        description: `Website's About page`,
      }}
    >
      <div >
        <main>
          <h1>{t("title")}</h1>
        </main>
      </div>
    </Page>
  );
};

export default About;

Source Code.