The useLocale
hook
corgi's built-in React hook, useLocale
allows you to easily pull in various pieces of locale-specific data from within your functional React components.
General usage
For the most part, you can use the useLocale
hook as shown here. This example destructures the returned object, into just the globals
and page
objects.
import { useLocale } from "@local/hooks";
const MyComponent = () => {
const { globals, page } = useLocale();
console.log(globals);
console.log(page);
return null;
};
Usage at the page-component level
If using this hook at the page-level—i.e. from a component defined as a page within the /src/pages/
directory—you must pass the locale folder name to the hook. This acts a sort of "initialization" step for the hook. All lower-level uses of the hook do not require this step. In this example, we're looking at an imaginary About page component. The locale folder name is declared at the top of the file, and is then passed into the useLocale
hook:
import { useLocale } from "@local/hooks";
const LOCALE_FOLDER = "about";
// for nested pages, this might look more like "work/advertising"
const AboutPage = () => {
const { globals, page } = useLocale(LOCALE_FOLDER);
console.log(globals);
console.log(page);
return null;
};
Available properties
The useLocale
hook returns a number of other useful properties, all of which are outlined below.
Property | Type | Description |
---|---|---|
pageName | String | The current page's directory name. This is the same as the locale folder name. |
locale | String | The current locale string ("en" , for example). |
localeMap | Object | The localeMap data as specified in /src/config-locales.js , for the current locale. |
page | Object | The page-level locale data, for the current page and locale. |
globals | Object | The site-wide locale data, for the current locale. |
alternativeLocales | Array | A list of all available locales for the page, excluding the current locale. |