Using `next-translate` is a more streamlined approach to handling internationalization (i18n) in Next.js. Here’s a step-by-step guide to implement it for both static and dynamic content:
### 1. Setup Next.js with `next-translate`
1. **Install `next-translate`:**
```bash
npm install next-translate
```
2. **Create the `i18n.js` configuration file:**
```javascript
// i18n.js
module.exports = {
locales: ['en', 'es', 'fr'], // Add your supported languages here
defaultLocale: 'en',
pages: {
'*': ['common'], // Load common namespace for all pages
},
};
```
3. **Update `next.config.js` to include the `next-translate` configuration:**
```javascript
// next.config.js
const nextTranslate = require('next-translate');
module.exports = nextTranslate({
// Other Next.js configurations
});
```
### 2. Translating Static Content
1. **Create a folder structure for your translations:**
```
/locales
/en
common.json
/es
common.json
/fr
common.json
```
2. **Add translation files (`common.json`):**
```json
// locales/en/common.json
{
"greeting": "Hello",
"welcome": "Welcome to our website"
}
// locales/es/common.json
{
"greeting": "Hola",
"welcome": "Bienvenido a nuestro sitio web"
}
// locales/fr/common.json
{
"greeting": "Bonjour",
"welcome": "Bienvenue sur notre site Web"
}
```
3. **Use `useTranslation` hook in your components:**
```javascript
// pages/index.js
import useTranslation from 'next-translate/useTranslation';
const HomePage = () => {
const { t } = useTranslation('common');
return (
<div>
<h1>{t('greeting')}</h1>
<p>{t('welcome')}</p>
</div>
);
};
export default HomePage;
```
### 3. Translating Dynamic Content from API
For dynamic content, you can fetch data from your API and use the translations provided by `next-translate`.
1. **Fetch data in `getStaticProps` or `getServerSideProps`:**
```javascript
// pages/[id].js
import useTranslation from 'next-translate/useTranslation';
export async function getStaticProps({ params, locale }) {
const res = await fetch(`https://api.example.com/data/${params.id}?lang=${locale}`);
const data = await res.json();
return {
props: {
data,
},
};
}
export async function getStaticPaths() {
const res = await fetch('https://api.example.com/data');
const items = await res.json();
const paths = items.map((item) => ({
params: { id: item.id },
locale: 'en', // Add other locales if needed
}));
return { paths, fallback: false };
}
const ItemPage = ({ data }) => {
const { t } = useTranslation('common');
return (
<div>
<h1>{data.title}</h1> {/* Assuming the API returns localized content */}
<p>{data.description}</p> {/* Assuming the API returns localized content */}
</div>
);
};
export default ItemPage;
```
### 4. Handling Locale Changes
To handle locale changes dynamically, you can use a language switcher component.
1. **Create a LanguageSwitcher component:**
```javascript
// components/LanguageSwitcher.js
import { useRouter } from 'next/router';
import i18nConfig from '../i18n';
const LanguageSwitcher = () => {
const router = useRouter();
const { locales, locale: currentLocale } = router;
const { pathname, asPath, query } = router;
const changeLanguage = (e) => {
const locale = e.target.value;
router.push({ pathname, query }, asPath, { locale });
};
return (
<select onChange={changeLanguage} defaultValue={currentLocale}>
{locales.map((locale) => (
<option key={locale} value={locale}>
{locale}
</option>
))}
</select>
);
};
export default LanguageSwitcher;
```
2. **Use the LanguageSwitcher in your layout:**
```javascript
// pages/_app.js
import LanguageSwitcher from '../components/LanguageSwitcher';
import '../styles/globals.css';
function MyApp({ Component, pageProps }) {
return (
<>
<LanguageSwitcher />
<Component {...pageProps} />
</>
);
}
export default MyApp;
```
By following these steps, you can implement internationalization in your Next.js project using `next-translate`, efficiently handling both static and dynamic content translations.