Monday, March 2, 2020

Detect Locale Change in React i18next

Leave a Comment
I was looking for a way to re-render Chart.js charts when the react-i18next locale was changed. Looking through their documentation at https://react.i18next.com/ I didn't see any hook that could be used to detect current locale.

Problem

When the translation language is changed I also change the moment.js locale for my time-series charts in Chart.js. I need a way to detect language changes so I can rerender the charts.

Solution

Add the locale ISO code into the translation files and use that.
What I did was:
  1. Add a new translation key in my translation files: 'current_locale': 'en' for the English translation, 'current_locale': 'ro' for Romanian.
  2. Use the useTranslation() hook:
    const { t } = useTranslation();
    
  3. Rerender the chart when language is changed:
    useEffect(() => {
       // This will be now called when the locale is changed
    }, [t('current_locale')])
    

Improvements

You can also create a custom hook if you want:
export const useLocale = () => {
    const { t } = useTranslation();
    return t('current_locale');
};
Now you can use the locale value directly:
const locale = useLocale();
useEffect(() => {
   // This will be now called when the locale is changed
}, [locale])

0 comentarii:

Post a Comment