# How to add i18n routing
# Routing Synced With I18n
- Open the
next.config.jsfile and add thei18property with the languages you need
i18n: {
locales: ['en', 'fr', 'ar'],
defaultLocale: 'en'
},
- Create a
useEffectin thesrc/pages/_app.tsxfile 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
localeparameter withrouter.push:
- Import
localefrom theuseRouterhook and add thelocaleprop 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&getStaticPropsin 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,
}
}