Changing languages

How to configure and switch between languages in your React app

Language switching lets users choose their preferred locale for your application’s content. GT React offers several approaches, from simple programmatic switching to pre-built UI components for custom language selectors.

Available methods

Using the useSetLocale hook

The useSetLocale hook lets you change your app’s language:

import { useSetLocale } from 'gt-react';

export default function MyComponent() {
  const setLocale = useSetLocale();

  return <button onClick={() => setLocale('en')}>Set locale</button>;
}

Simply pass the locale you want to switch to as the argument to the function returned by the hook.

Using the <LocaleSelector> component

The <LocaleSelector> component provides a ready-to-use drop-down that automatically shows all configured locales:

import { LocaleSelector } from 'gt-react';

export default function MyComponent() {
  return <LocaleSelector />;
}

This component automatically:

  • Shows all configured locales for your project
  • Displays locales in their native language names
  • Handles the switching logic
  • Maintains the current selection state

Using the useLocaleSelector hook

If you want to build your own custom locale selector component, use useLocaleSelector:

import { useLocaleSelector } from 'gt-react';

function CustomLocaleSelector() {
  const { 
    locale,              // Current active locale (e.g., 'en', 'es')
    locales,             // Array of locales your project supports ['en', 'es', 'fr']
    setLocale,           // Function to change the locale: setLocale('es')
    getLocaleProperties  // Function to get display information for a locale
  } = useLocaleSelector();
  
  if (!locales?.length) return null;
  
  return (
    <select 
      value={locale || ''} 
      onChange={(e) => setLocale(e.target.value)}
    >
      {locales.map((loc) => {
        const props = getLocaleProperties(loc);
        return (
          <option key={loc} value={loc}>
            {props.nativeNameWithRegionCode} {/* e.g., "English (UK)", "Español (ES)" */}
          </option>
        );
      })}
    </select>
  );
}

Important notes

GTProvider requirement

Language-switching components must be used within a <GTProvider>:

// ✅ Correct
<GTProvider>
  <LanguageSwitcher />
</GTProvider>

// ❌ Incorrect - outside provider
<LanguageSwitcher />

Next steps

How is this guide?

Changing languages