useGT()
API Reference for the useGT hook
Overview
useGT()
is used to access translations from the translation dictionary.
It must be used within a component wrapped by a <GTProvider>
.
useGT()
supports:
- Translation of string and jsx content.
- Variable insertion and conditional logic within translations.
- Optional id prefixing.
useGT()
and useElement()
use a dictionary to store all content for translation.
This is different from using the <T>
component for translation.
If you are interested in only using <T>
components for translation, then this document is not relevant.
Reference
Parameters
Prop | Type | Default |
---|---|---|
id? | string | undefined |
Description
Prop | Description |
---|---|
id | An optional prefix to prepend to all translation keys. This is useful for working with nested dictionary values. |
Returns
A translation function t
with the following signature:
key
: The identifier of the translation to fetch.- Returns: The translated value as a
React.ReactNode
.
Examples
Basic Usages
Every entry in your dictionary gets translated. Entries can be either JSX or a string.
When we want to access these entries, we call useGT()
.
This returns a function that accepts the key of a translation from the dictionary.
Using variables
You can pass variables to dictionary translations.
For jsx content, just use a variable component.
For string content, add curley braces {}
to the string.
Whenever you have a variable in your jsx translations,
NEVER insert variables directly into the jsx.
ALWAYS use a variable component:
<Currency>
, <DateTime>
, <Num>
, or <Var>
.
In order to pass values, you must (1) assign an identifier and (2) reference the identifier when calling the t()
function.
In this example, we use <Var>
and {}
to pass variables to the translations.
In the dictionary, we assign identifiers name="userName"
and {userName}
.
In the component, we pass the values userName: "Alice"
and userName: "Bob"
.
Using branches
Branching components, such as <Branch>
and <Plural>
,
can be used to handle control logic in a translation.
In order to pass values, you must (1) assign an identifier and (2) reference the identifier when calling the t()
function.
In this example, we see that hairColor
is passed to both <Branch>
and <Var>
components.
Using prefixes
We can use prefixes to only translate a subset of the dictionary.
Because we added the value 'prefix1.prefix2'
to the useGT
hook, all of the keys are prefixed with prefix1.prefix2
:
Notes
- The
useGT()
function allows you to access dictionary translations. - The
useGT()
hook can only be used within a component wrapped by a<GTProvider>
component. - Supports dynamic behavior and variable insertion with Branching and Variable Components respectively.
Next Steps
- Learn more about using dictionaries in the dictionaries reference.
- See
useElement()
for rendering jsx content. - Enhance server-side locale routing with i18n Routing and locale management with i18n Configuration.