Search code examples
reactjsi18nextreact-i18next

i18next React - Changing language only works after browser refresh


On my React page, changing the language only works after browser refresh. Have tried all possible suggestions from previous posts and nothing. It does work as expected only for strings on the App.js component. Any help appreciated.

here is my i18n.js file

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

const resources = {
    'en': {translation: require('./translations/en.json')},
    'th': {translation: require('./translations/th.json')},
    'pt': {translation: require('./translations/pt.json')},
}

i18n
  // detect user language
  // learn more: https://github.com/i18next/i18next-browser-languageDetector
  .use(LanguageDetector)
  // pass the i18n instance to react-i18next.
  .use(initReactI18next)
  // init i18next
  // for all options read: https://www.i18next.com/overview/configuration-options
  .init({
    debug: true,
    fallbackLng: 'en',
    // lng: 'th',
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    },
    resources
  });

export default i18n;

My change language function is this:

 handleLanguageChange = (item) => {
    i18n.changeLanguage(item.key, () => console.log('lanh1', i18next.language))
    // this.forceUpdate()
  }

Importing on App.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import rootReducer from './store/reducers/rootReducer';
import thunk from 'redux-thunk';
import { applyMiddleware, createStore } from 'redux';
import { Provider } from 'react-redux';

import './i18n';

const store = createStore(rootReducer, applyMiddleware(thunk));

ReactDOM.render(
  <Provider store={store}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Provider>,
  document.getElementById('root')
);

reportWebVitals();

and here is how i render translations:

import React, { Component } from 'react';
import { Navigate} from "react-router-dom";

import { Button, Container, Grid } from '@mui/material';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { setCurRoute } from '../../store/actions/authAction';
import Background from '../../img/header-img.jpg';
import i18next from 'i18next';
// import i18n from '../../i18n';

class LandingPage extends Component {
  render() {
    return (
        <div
          style={{
          backgroundImage: `url(${Background})`,
          backgroundPosition: 'center',
          backgroundSize: 'cover',
          backgroundRepeat: 'no-repeat'
          }}
        >
          <h1 style={{textAlign: 'center'}}>{i18next.t('headline_one_one')}<br />{i18next.t('headline_one_two')}</h1>
          <h4 style={{textAlign: 'center', lineHeight: 2, border: '2'}}>
            {i18next.t('headline_two')}
          </h4>
        </div>
    );
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(LandingPage)

Solution

  • In react, try to use the useTranslation hook or the withTranslation HOC. That will detect the language change.