Reputation: 323
I'm having an issue trying to do reactive translations with i18next on React.
These are the important files:
i18n/index.js
import i18next from 'i18next';
import en from './en.json';
import es from './es.json';
import it from './it.json';
const i18n = i18next.init({
interpolation: {
// React already does escaping
escapeValue: false,
},
lng: 'en',
// Using simple hardcoded resources for simple example
resources: {
en: { translation: en },
es: { translation: es },
it: { translation: it }
},
});
/**
* Translates the given string code into the current language's representation.
*
* @param {string} text The string code to be translated.
* @returns {string} The translated text.
*/
export function t(text) {
return i18n.t(text);
}
/**
* Changes the app's current language.
*
* @param {string} language The language code, i.e: 'en', 'es', 'it', etc.
*/
export function changeLanguage(language) {
i18n.changeLanguage(language, (err) => {
if (err) {
console.log('Language error: ', err);
}
});
}
Flags.jsx
import React, { Component } from 'react';
import { changeLanguage } from '../../../../i18n';
import './Flags.css';
export default class Flags extends Component {
/**
* Constructor.
*
* @param {any} props The components properties.
*/
constructor(props) {
super(props);
this.changeLang = this.changeLang.bind(this);
}
/**
* Changes the app's current language.
*
* @param {string} language The language code, i.e: 'en', 'es' or 'it'.
*/
changeLang(language) {
changeLanguage(language);
alert('language change: ' + language);
}
/**
* Renders this component.
*
* @returns {string} The components JSX code.
*/
render() {
return (
<li role="presentation">
<div className="flags">
<button onClick={ () => this.changeLang('en') }>
<span className="flag-icon flag-icon-us"></span>
</button>
<button onClick={ () => this.changeLang('es') }>
<span className="flag-icon flag-icon-es"></span>
</button>
<button onClick={ () => this.changeLang('it') }>
<span className="flag-icon flag-icon-it"></span>
</button>
</div>
</li>
);
}
}
I think the change of language is working but is not acting in a reactive way because when I make click in a flag the change isn't reflected in the UI. How could I accomplish that?
Upvotes: 0
Views: 1560
Reputation: 447
component doesn't show updated language because it does not re-render
correct implementation should pass new props to components that use translation but seems they are not
(...to get component updated you need to pass language as a prop or keep it in the state, and on change of language component will then rerender)
so take a look at using wrapper component https://react.i18next.com/latest/translation-render-prop or provider or similar https://react.i18next.com/latest/i18nextprovider because it does not look like you are wrapping your components like in examples
Upvotes: 1