I have some problems with I18N and NextJS. So I configured my I18N, everything works with default locale, but everything crashes if I want to change locale from local storage.
In _app.js I tried to use this function:
const { i18n } = useTranslation();
useEffect(() => {
if(localStorage.getItem('Locale')) {
i18n.changeLanguage(localStorage.getItem('Locale'))
}
}, [])
I have imported:
import './I18N/i18next';
import { useTranslation } from 'react-i18next'
When app is loaded it crashes and give error:
The above error occurred in the <MyApp> component:
at MyApp (webpack-internal:///./pages/_app.js:35:24)
at ErrorBoundary (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ErrorBoundary.js:23:47)
at ReactDevOverlay (webpack-internal:///./node_modules/@next/react-dev-overlay/lib/internal/ReactDevOverlay.js:73:23)
at Container (webpack-internal:///./node_modules/next/dist/client/index.js:146:5)
at AppContainer (webpack-internal:///./node_modules/next/dist/client/index.js:623:24)
at Root (webpack-internal:///./node_modules/next/dist/client/index.js:739:25)
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
I’m using the newest Next.js and I18N
What I found is that the program crashes when code reaches i18n.changeLanguage(‘en’). If I use the button to set a new locale, the same error happens. I know that next.js have the option to read locale from URL, but I want to use locale from local storage. Is it possible to use I18N in next js that way? I found too that if I console log i18n it gives me back that i18n have changeLanguage function.
Thanks, everyone for responding! I don’t know what to do at all 🙁
Updated: next.config.js:
const withLess = require('@zeit/next-less');
const withSass = require('@zeit/next-sass');
module.exports = withSass(withLess({
lessLoaderOptions: {
javascriptEnabled: true
}
}))
Advertisement
Answer
You can change the default local in next.config.js
in _app.js
you can get the local in router
const router = useRouter();
const { locale } = router;
const { i18n } = useTranslation();
useEffect(() => {
i18n.changeLanguage(locale);
}, [locale]);
i suppose that you have two locales(fr, en)
next.config.js
const withLess = require('@zeit/next-less');
const withSass = require('@zeit/next-sass');
module.exports = withSass(withLess({
lessLoaderOptions: {
javascriptEnabled: true
},
i18n: {
locales: ["fr", "en"],
defaultLocale: "fr",
},
}))