next-i18next

쌍제이(JJVoiture)·2022년 4월 13일
0

next-i18next

next-i18next는 Next.js에서 다국어 기능을 구현하기 위한 라이브러리이다.

appWithTranslation

_app

import { appWithTranslation } from 'next-i18next';

const MyApp = ({ Component, pageProps }) => <Component {...pageProps} />;

export default appWithTranslation(MyApp);

appWithTranslation는 _app에 정의된 component를 i18nextProvider를 추가한 고차 컴포넌트(HOC)로 만드는 역할을 한다.

serverSideTranslations

import { serverSideTranslations } from 'next-i18next/serverSideTranslations';

export async function getStaticProps({ locale }) {
  return {
    props: {
      ...(await serverSideTranslations(locale, ['common', 'footer'])),
      // Will be passed to the page component as props
    },
  };
}

serverSideTranslations는 page에 translation 및 configuration option을 pass하는 역할이다.

export declare type SSRConfig = {
    _nextI18Next: {
        initialI18nStore: any;
        initialLocale: string;
        userConfig: UserConfig | null;
    };
};

useTranslation

import { useTranslation } from "next-i18next";

export const Home = () => {
  const { t } = useTranslation("common");

  return (
    <div>
      <p>{t("Header")}</p>
    </div>
  );
};

useTranslation은 namespace에 해당하는 key의 value를 가져오는 hook으로
next-i18next의 함수가 아니라 react-i18next에 정의된 hook이다.


useTranslation이 작동하기 위해서는 pages 컴포넌트에서 serverSideTranslations을 통해 option을 전달 받아야 한다.
따라서 pages component보다 상위에 정의된 컴포넌트에서는 useTranslation을 사용할 수 없다는 문제점이 있다...

profile
안녕하세요. 중구난방 개발자 쌍제이입니다.

0개의 댓글