React i18next get language in utility function

problem

I'm using react-i18next in a React app.

As in the Quick Start guide, I can easily get the current language in a function component, with the useTranslation hook:

import { useTranslation } from 'react-i18next';

...

const { t, i18n } = useTranslation();
const language = i18n.language;

But how to get it in a utility function, where I can't use the hook?

solution

You can get it by importing i18next:

import i18next from 'i18next';

export function getMessage(): string {
  const language = i18next.language;
  ...
}
Gravatar
Author
Dan Dumitru
Last Edit
Mar 12, 2023 at 09:03

Your Comment

Feel free to post additional info or improvement suggestions.
preview
Optional, never shown, displays gravatar.

Formatting Tips

This editor uses Markdown to easily add code in your posts.

Triple backticks for full line(s) of code (or indent 4 spaces)

```
let foo = 'bar';
```

[link text](http://a.com)

*italic* **bold**

More Tips