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: March 12, 2023
Last Edit March 12, 2023
Created March 12, 2023
Views 67
Tags
React

Join in!

I'm building here a library of useful solutions to software development problems.

If you like this project, create an account or add a bookmark, then come back here to write a post yourself when you run into something that might be useful to others...

>> read more

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