Select
Estimated reading time: 3 minutes
The select
function is a tool for handling pluralization and conditional text selection in translations. It allows you to define different text variants based on a specific variable's value.
Plural functions is under the hood using
select
to handle the pluralization.
key
: The variable name to base the selection on (e.g., 'count', 'fruit')options
: An object containing the different text variants
Examples
Pluralization
Don't forget to use
as const
for the options object.other
is a required key for the default translation. In this example, the text changes based on thecount
value:
- If
count
is 0, it returns "You have no messages" - If
count
is 1, it returns "You have 1 message" - For any other value, it returns "You have {{count}} messages", where
{{count}}
will be replaced with the actual number
Combining with Other Variables
This example combines the count
selection with another variable {{name}}
, allowing for more complex translations.
Non-numeric Selection
The select
function can also be used with non-numeric keys. In this case, it selects based on the fruit
value:
- If
fruit
is "apple", it returns "I like apples" - If
fruit
is "banana", it returns "I enjoy bananas" - For any other fruit, it returns "I prefer {{fruit}}", where
{{fruit}}
will be replaced with the actual fruit name
Usage with Translators
When used with a translator function, you can easily generate the appropriate text:
The select
function provides a flexible way to handle various translation scenarios, from simple pluralization to more complex conditional text selection.