Monday, March 2, 2020

Detect Locale Change in React i18next

2 comments
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])

2 comments:

  1. There's a cleaner solution:

    const { i18n } = useTranslation();
    // Then use the i18n.language you don't need to store any key anywhere

    useEffect(() => {
    // This will be now called when the locale is changed
    }, [i18n.language]);


    ReplyDelete
    Replies
    1. Thanks for pointing this out!

      Do you know if it was always there or was it introduced recently? I remember that I searched for something like this but couldn't find it at the time of writing this post.

      Delete