Setup
ℹ️
Make sure you've followed the Get Started documentation before continuing!
Create locale filesMake
Make sure that you've set up correctly the i18n
key inside next.config.js
(opens in a new tab), then create locales/index.ts
with your locales:
// locales/index.ts
import { createI18n } from 'next-international'
export const { useI18n, useScopedI18n, I18nProvider, getLocaleProps } = createI18n({
en: () => import('./en'),
fr: () => import('./fr')
})
Each locale file should export a default object (don't forget as const
):
// locales/en.ts
export default {
'hello': 'Hello',
'hello.world': 'Hello world!',
'welcome': 'Hello {name}!'
} as const
Setup provider
Wrap your whole app with I18nProvider
inside _app.tsx
:
// pages/_app.tsx
import { I18nProvider } from '../locales'
import { AppProps } from 'next/app'
export default function App({ Component, pageProps }: AppProps) {
return (
<I18nProvider locale={pageProps.locale}>
<Component {...pageProps} />
</I18nProvider>
)
}
You can also provide a fallback
component prop to show while waiting for the locale to load, and a fallbackLocale
prop to specify a locale to fallback on if a key has not been translated.
Translate
Use useI18n
and useScopedI18n()
:
// pages/index.ts
import { useI18n, useScopedI18n } from '../locales'
// export const getStaticProps = ...
// export const getServerSideProps = ...
export default function Page() {
const t = useI18n()
const scopedT = useScopedI18n('hello')
return (
<div>
<p>{t('hello')}</p>
{/* Both are equivalent: */}
<p>{t('hello.world')}</p>
<p>{scopedT('world')}</p>
<p>{t('welcome', { name: 'John' })}</p>
<p>{t('welcome', { name: <strong>John</strong> })}</p>
</div>
)
}
What's next?
Learn how to add plurals, use scoped translations, and setup Static Site Generation.