# How to add i18n routing
# Routing Synced With I18n
- Open the
next.config.js
file and add thei18
property with the languages you need
i18n: {
locales: ['en', 'fr', 'ar'],
defaultLocale: 'en'
},
- Create a
useEffect
in thesrc/pages/_app.tsx
file to watch changes of i18n language and to preserve the language in case the page is reloaded:
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import { useTranslation } from 'react-i18next'
const App = () => {
const router = useRouter()
const { i18n } = useTranslation()
const { locale } = router
useEffect(() => {
if (locale !== 'en') {
i18n.changeLanguage(locale)
}
}, [locale])
return (
...
)
}
export default App
- To switch a language, push the
locale
parameter withrouter.push
:
- Import
locale
from theuseRouter
hook and add thelocale
prop to every NextJS link that is used in your app:
import Link from 'next/link'
import { useRouter } from 'next/router'
const Component = () => {
const router = useRouter()
const { locale } = router
return <Link href='...' locale={locale}>text</Link>
}
export default Component
- If you have
getStaticPaths
&getStaticProps
in your component then you'll have to do the following otherwise you'll be redirected to404
export const getStaticProps = ({ locale, locales }) => {
return {
props: {
locale,
locales,
},
}
}
export const getStaticPaths = ({ locales }) => {
const paths = []
for (const locale of locales) {
paths.push({ params: { ... }, locale })
paths.push({ params: { ... }, locale })
}
return {
paths,
fallback: true,
}
}