In this article, I will demonstrate how to localize your Next.js project using its built-in internationalization (i18n) support, without the need for any third-party packages.
To get started, follow these steps:
- Open the
next.config.js
file and add the followingi18n
object: ```javascript
const nextConfig = {
reactStrictMode: true,
i18n: {
defaultLocale: "en",
locales: ["en", "ar"],
localeDetection: false,
},
};
module.exports = nextConfig;
2. Create a new directory named localization in the src directory and add the following files inside it:
`index.js`
`en.json`
`ar.json`
In `en.json` and `ar.json`, define your localized strings as key-value pairs.
For example, `en.json`:
```json
{
"greet": "Hello"
}
And ar.json
:
{
"greet": "مرحبا"
}
- In
index.js
, import the localization files and create a custom hook for functional components and a HOC for class components to access the localized strings:
import en from "./en.json";
import ar from "./ar.json";
import { useRouter } from "next/router";
import { useCallback } from "react";
const locales = { en, ar };
const useTranslation = () => {
const router = useRouter();
const changeLanguage = (locale) => {
if (locale !== router.locale) {
// We change the language
// and push the new route to the router
router.push(
{
route: router.pathname,
query: router.query,
},
router.asPath,
{ locale }
);
}
};
/*
We receive the string and
return the localized string,
If the string is not found in the localization
file it will return the original string
*/
const t = useCallback(
(str) => locales[router.locale][str] || str,
[router.locale]
);
return { t, changeLanguage, currentLanguage: router.locale };
};
const withTranslation = (Component) => (props) => {
const { t, changeLanguage, currentLanguage } = useTranslation();
return (
<Component
{...props}
t={t}
changeLanguage={changeLanguage}
currentLanguage={currentLanguage}
/>
);
};
export { useTranslation, withTranslation };
That's it! Now you can easily localize your Next.js project using its built-in i18n support.
Here's an example too
I'm the example
Top comments (8)
zor jwana taman drezh be
zor supas
Efficient and lightweight code Without installing any third party packages. 🚀🚀
Thank you for your kind words!
It's amazing that it's working with out any third party and you have done everything about performance in it , it's mind blowing and it helps a lot.
I appreciate your feedback, I am glad that it has been helpful to you.
this is great, thanks for sharing your experince Kak.
You're welcome! It was my pleasure.