乐闻世界logo
搜索文章和话题

How to get current language next i18next?

1个答案

1

When using the next-i18next library, retrieving the current language can be done in multiple ways, depending on whether you are working in a server-side or client-side context, and whether you are within a page component or outside of it. The following are some methods to retrieve the current language:

1. Using the useTranslation Hook

If you are working with a React functional component, you can use the useTranslation Hook to retrieve the current language. The object returned by useTranslation includes an i18n instance, from which you can access the current language settings.

javascript
import React from 'react'; import { useTranslation } from 'next-i18next'; const MyComponent = () => { const { i18n } = useTranslation(); // Retrieve the current language const currentLanguage = i18n.language; return <p>Current language: {currentLanguage}</p>; }; export default MyComponent;

2. Using the withTranslation Higher-Order Component

If you are using a class component or prefer a Higher-Order Component (HOC) approach to retrieve the current language, you can use withTranslation. This injects the i18n instance into your component's props:

javascript
import React from 'react'; import { withTranslation } from 'next-i18next'; class MyComponent extends React.Component { render() { // Access the i18n instance from props const { i18n } = this.props; // Retrieve the current language const currentLanguage = i18n.language; return <p>Current language: {currentLanguage}</p>; } } export default withTranslation()(MyComponent);

3. Using getInitialProps or getServerSideProps

In page-level components, you can retrieve the current language using Next.js's server-side rendering methods. getInitialProps or getServerSideProps receive a context object that includes req (on the server), from which you can read the current language:

javascript
import { getServerSideProps } from 'next-i18next/serverSideTranslations'; export const getServerSideProps = async ({ locale }) => { // The locale variable contains the current language environment return { props: { // Pass the current language to the page component language: locale, }, }; }; // Then use this prop in the page component const MyPage = ({ language }) => { return <p>Current language: {language}</p>; }; export default MyPage;

4. Using Router or useRouter Hook

In next/router, the Router object or the useRouter Hook returns an object that includes the current language information:

javascript
import { useRouter } from 'next/router'; const MyComponent = () => { const router = useRouter(); // Retrieve the current language const currentLanguage = router.locale; return <p>Current language: {currentLanguage}</p>; }; export default MyComponent;

Using any of the above methods, you can effectively retrieve the current language setting and perform internationalization operations accordingly in your application.

2024年6月29日 12:07 回复

你的答案