LanguageSelector
This is a language selector utilising @ntds/sticky to persist the language choice accross React components, pages, etc.
This component accepts an onChange property, which is a function that performs the translation whenever the user changes language. Translation can be done using any translation library, since you will always provide the language selector with the appropriate translation functionality in the onChange property.
This component provides two constants for English (Language.ENGLISH) and Norwegian (Language.NORWEGIAN). The default language is Norwegian.
Selected language will be persisted in the browsers localStorage using the key ntds-language-selector. This will make the language selection stay persisted accross different apps on the same domain.
Example:
Basic Usage
This example shows how you can do translation using your own custom translation logic.
In this example we only update the text value whenever the language is changed.
Usage With i18next and useTranslation
In Omniweb translation is done with i18next and react-i18next, using the useTranslation hook.
To use the language selector with this translation library the translation functionality must be initialized and translation function must be provided using the onChange prop.
Example:
Customizing the Size of the Component
The component size can be customized by adjusting the size of the flag icons.
You can set the flagIconSize prop to control the flag size, which supports predefined IconSize values (sm, md, ...),
or custom Tailwind CSS classes for more flexibility.
Changing Initial Language
The language selector defaults to Norwegian or to the value stored in localStorage (if available).
Use the initialLanguage prop to set a different starting language, which will be applied when the component renders for the first time.
This prop is crucial for Next.js applications, where the language is determined by the locale specified in the URL (e.g., en or no).
In such cases, the initialLanguage prop ensures that the language is correctly set on the first render, overriding any values stored in sticky state or localStorage to prevent potential hydration errors.
Example:
Supported Languages
The language selector supports English and Norwegian.
Props
LanguageSelector
| Prop | Type & Description |
|---|---|
| initialLanguage | Language Specifies the language which should be used on first render. |
| position | "right" | "left" Default value: "right" Specifies the alignment of the dropdown itself. |
| onChange | (language: Language) => void Callback function that is called on initial render and when the language is changed. |
| flagIconSize | IconSize | TwSizingClass Default value: "lg" Specifies the size of the flag icons. Can either be an IconSize or a Tailwind CSS sizing class. Examples:
|
| chevronIconSize | IconSize Default value: "xs" Specifies the size of the chevron icon. |