I\'m trying to figure out how to change language using React-Intl. This is my first React App and it has been made with create-react-app, I\'m not using Redux nor Flux.
It works if you remove all from root:
ReactDOM.render( , document.getElementById('root'));
But now we change TodoApp component like this:
1) We add 'locale' as component state and import React-Intl:
import { IntlProvider, addLocaleData } from 'react-intl';
import intlEN from 'react-intl/locale-data/en';
import intlES from 'react-intl/locale-data/es';
import intlMessagesES from './../i18n/locales/es.json';
import intlMessagesEN from './../i18n/locales/en.json';
addLocaleData([...intlEN, ...intlES]);
/* Define your default translations */
let i18nConfig = {
locale: 'en',
messages: intlMessagesEN
};
2) Change our changeLanguage function (this time called 'onChangeLanguage'), this function receives 'lang' from a subComponent language selector:
onChangeLanguage(lang) {
switch (lang) {
case 'ES': i18nConfig.messages = intlMessagesES; break;
case 'EN': i18nConfig.messages = intlMessagesEN; break;
default: i18nConfig.messages = intlMessagesEN; break;
}
this.setState({ locale: lang });
i18nConfig.locale = lang;
}
And finally render:
render() {
return (
// Other components ...
);
}
If someone doesn't understand at all, ask in comments! Thanks to @TomásEhrich