Skip to main content

usePreferredLanguage

Every example on this page is live, drawn by the library's Storybook, where you can also change its props and see the result.

This hook returns the language the frame's owner picked in their Frame Settings, so your widget can show its own words in that language.

Import​

import { usePreferredLanguage } from "~lib/use-preferred-language";

API​

const language = usePreferredLanguage();

Parameters​

This hook takes no parameters.

Return Value​

NameTypeDescription
languageLanguageA language code: "en", "fr", "de", "it", "es" or "ja"

A language is always returned. A frame left on Automatic, and the Studio preview, return "en".

Dates and Numbers​

Dates and numbers are already written in the frame's language, so they do not need this hook. Leave the language out of toLocaleDateString, toLocaleString or any Intl formatter, and they use the frame's. When you pass options, put undefined where the language would go:

const date = scheduledDate.toLocaleDateString(undefined, {
weekday: "long",
day: "numeric",
month: "long",
});

Name a language, such as "en-GB", only when you want that one on every frame.

Example​

For your widget's own words, keep a translation of each and fall back to English for a language you have not translated:

import { usePreferredLanguage } from "~lib/use-preferred-language";
import { useScheduledDate } from "~lib/use-scheduled-date";
import { useTimeZone } from "~lib/use-time-zone";

const GREETINGS: Record<string, string> = {
en: "Good morning",
fr: "Bonjour",
ja: "おはようございます",
};

const Widget = () => {
const language = usePreferredLanguage();
const scheduledDate = useScheduledDate();
const timeZone = useTimeZone();

const date = scheduledDate.toLocaleDateString(undefined, {
timeZone,
weekday: "long",
day: "numeric",
month: "long",
});

return (
<div className="flex h-full w-full flex-col items-center justify-center">
<h1 className="text-4xl">{GREETINGS[language] ?? GREETINGS.en}</h1>
<p className="text-2xl">{date}</p>
</div>
);
};

Examples​

Any Language​

Open Default in Storybook

Every Language​

Open Every Language in Storybook

See Also​