@lingui/react
v6.8.0
Published
React bindings for Lingui i18n: I18nProvider, Trans and useLingui, with compile-time macros and React Server Components support
Readme
@lingui/react
React bindings for Lingui i18n: I18nProvider, Trans and useLingui, with compile-time macros and React Server Components support
@lingui/react is part of Lingui. Lingui is a lightweight, open-source internationalization (i18n) library for JavaScript and TypeScript. It brings compile-time macros and a CLI for message extraction to React, React Native, Vue, SolidJS, Astro, Svelte, and Node.js.
The package has the following entry points:
@lingui/reactexportsI18nProvider, theTranscomponent and theuseLinguihook. The provider puts ani18ninstance from@lingui/coreinto React context.@lingui/react/macroexports theTrans,Plural,Selectand related macros, which generate the ICU message and its ID from JSX at build time, and auseLinguimacro whosettranslates strings outside JSX. Macros need the Babel or SWC plugin.@lingui/react/serverexportssetI18nfor React Server Components, whereTransanduseLinguiread that instance instead of context. The same component renders on the server and on the client.
Installation
npm install @lingui/core @lingui/react@lingui/core provides the i18n instance passed to the provider. The installation guide covers the macro plugin and the lingui.config.js file.
Usage
import { i18n } from "@lingui/core"
import { I18nProvider } from "@lingui/react"
import { Trans, useLingui } from "@lingui/react/macro"
import { messages } from "./locales/en/messages"
i18n.load("en", messages)
i18n.activate("en")
function Welcome({ name }) {
const { t } = useLingui()
return (
<>
<img src="/logo.svg" alt={t`Lingui logo`} />
<Trans>
Welcome back, {name}. Read the <a href="/docs">documentation</a>.
</Trans>
</>
)
}
export function App() {
return (
<I18nProvider i18n={i18n}>
<Welcome name="Fred" />
</I18nProvider>
)
}The Trans block becomes a single message, Welcome back, {name}. Read the <0>documentation</0>., where <0> stands for the link. lingui extract from @lingui/cli writes the messages into the catalogs and lingui compile produces the messages module imported above.
Continue with the React tutorial, the Next.js App Router tutorial for Server Components or the React Native tutorial. See the React reference and the macro reference for the full API.
License
This package is licensed under the MIT license.
