This is my code.
import React, { Suspense } from 'react';
import { useTranslation } from 'react-i18next';
function Page() {
const { t, i18n } = useTranslation();
const changeLanguage = lng => {
i18n.changeLanguage(lng);
};
return (
<div className="App">
<div className="App-header">
<button onClick={() => changeLanguage('de')}>de</button>
<button onClick={() => changeLanguage('en')}>en</button>
</div>
<div>{t('test')}</div>
</div>
);
}
export default function App() {
return (
<Suspense fallback={<div>loading...</div>}>
<Page />
</Suspense>
);
}
when I click on the de en
button. I get this error. TypeError: i18n.changeLanguage is not a function.How to fix?
Looks like you haven't configured i18next
.
You will need to create a file i18n.js
containing the following content:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-xhr-backend';
import LanguageDetector from 'i18next-browser-languagedetector';
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
fallbackLng: 'en',
debug: true,
interpolation: {
escapeValue: false,
}
});
export default i18n;
Then import it in your index.js
:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import App from './App';
import './i18n';
ReactDOM.render(
<App />,
document.getElementById("root")
);