React-i18next
react-i18next is a powerful internationalization framework for React / React Native which is based on i18next.
Installation
Translate your content
Using the hook
Using the hook in functional components is one of the options you have.
The t function is the main function in i18next to translate content. Read the documentation for all the options.
import React from 'react';
// the hook
import { useTranslation } from 'react-i18next';
function MyComponent () {
const { t, i18n } = useTranslation();
return <h1>{t('Welcome to React')}</h1>
}
Learn more about the hook #useTranslation.
Using the HOC
Using higher order components is one of the most used method to extend existing components by passing additional props to them.
The t function is the main function in i18next to translate content. Read the documentation for all the options.
import React from 'react';
// the hoc
import { withTranslation } from 'react-i18next';
function MyComponent ({ t }) {
return <h1>{t('Welcome to React')}</h1>
}
export default withTranslation()(MyComponent);
Learn more about the higher order component #withTranslation.
Using the render prop
The render prop enables you to use the t function inside your component.
import React from 'react';
// the render prop
import { Translation } from 'react-i18next';
export default function MyComponent () {
return (
<Translation>
{
t => <h1>{t('Welcome to React')}</h1>
}
</Translation>
)
}
Learn more about the render prop #Translation.
Using the Trans component
The Trans component is the best way to translate a JSX tree in one translation. This enables you to eg. easily translate text containing a link component or formatting like .
import React from 'react';
import { Trans } from 'react-i18next';
export default function MyComponent () {
return <Trans><H1>Welcome to React</H1></Trans>
}
// the translation in this case should be
"<0>Welcome to React</0>": "<0>Welcome to React and react-i18next</0>"
Don't worry if you do not yet understand how the Trans component works in detail. Learn more about it here.
TypeScript Component
import * as React from 'react';
import { withTranslation, WithTranslation } from 'react-i18next';
class App extends React.Component<WithTranslation> {
render() {
return <h1>{this.props.t('greetMessage')}</h1>;
}
}
export default withTranslation()(App);
Nesting
Sample:
현재 언어 받아오기
withTranslation
의 i18n
Object 를 사용하면 된다.
import {withTranslation} from '../config/next-i18next';
const Home = function Home({ i18n }) {
return (<div>{i18n.language}</div>)
// ----------------^
};
APIs
useTranslation
withTranslation
Translation
Trans
I18nextProvider
import { I18nextProvider } from 'react-i18next';
import i18n from './i18n';
import App from './App';
<I18nextProvider i18n={i18n}>
<App />
</I18nextProvider>