Changing Languages

How to configure and switch between languages in your React app

Language switching allows users to change their preferred locale for your application's content. GT React provides several approaches from simple programmatic switching to pre-built UI components for custom language selectors.

Available Methods

Using the useSetLocale hook

The useSetLocale hook allows you to change the language of your app:

import { useSetLocale } from 'gt-react';

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

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

Simply provide the locale you want to change to as the argument to the function returned by the hook.

Using the <LocaleSelector> component

The <LocaleSelector> component provides a ready-to-use dropdown 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 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 info 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 (US)", "Español (ES)" */}
          </option>
        );
      })}
    </select>
  );
}

Important Notes

GTProvider Requirement

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

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

// ❌ Wrong - outside provider
<LanguageSwitcher />

Next Steps

How is this guide?

Changing Languages