1. Documentation
    2. Environment
    3. Intlayer with React CRA

    Getting Started Internationalizing (i18n) with Intlayer and React Create App

    What is Intlayer?

    Intlayer is an innovative, open-source internationalization (i18n) library designed to simplify multilingual support in modern web applications.

    With Intlayer, you can:

    • Easily manage translations using declarative dictionaries at the component level.
    • Dynamically localize metadata, routes, and content.
    • Ensure TypeScript support with autogenerated types, improving autocompletion and error detection.
    • Benefit from advanced features, like dynamic locale detection and switching.

    Step-by-Step Guide to Set Up Intlayer in a React Application

    Step 1: Install Dependencies

    Install the necessary packages using npm:

    bash
    1npm install intlayer react-intlayer
    bash
    1yarn add intlayer react-intlayer
    bash
    1pnpm add intlayer react-intlayer

    Step 2: Configuration of your project

    Create a config file to configure the languages of your application:

    typescript
    1// intlayer.config.ts 2 3import { Locales, type IntlayerConfig } from "intlayer"; 4 5const config: IntlayerConfig = { 6 internationalization: { 7 locales: [ 8 Locales.ENGLISH, 9 Locales.FRENCH, 10 Locales.SPANISH, 11 // Your other locales 12 ], 13 defaultLocale: Locales.ENGLISH, 14 }, 15}; 16 17export default config;

    To see all available parameters, refer to the configuration documentation here.

    Step 3: Integrate Intlayer in Your CRA Configuration

    Change your scripts to use react-intlayer

    json
    1 "scripts": { 2 "build": "react-intlayer build", 3 "start": "react-intlayer start", 4 "transpile": "intlayer build" 5 },

    Note: react-intlayer scripts are based on craco. You can also implement your own setup based on the intlayer craco plugin. See example here.

    Step 4: Declare Your Content

    Create and manage your content dictionaries:

    tsx
    1// src/app.content.tsx 2import { t, type DeclarationContent } from "intlayer"; 3import { type ReactNode } from "react"; 4 5const appContent = { 6 key: "app", 7 content: { 8 getStarted: t<ReactNode>({ 9 en: ( 10 <> 11 Edit <code>src/App.tsx</code> and save to reload 12 </> 13 ), 14 fr: ( 15 <> 16 Éditez <code>src/App.tsx</code> et enregistrez pour recharger 17 </> 18 ), 19 es: ( 20 <> 21 Edita <code>src/App.tsx</code> y guarda para recargar 22 </> 23 ), 24 }), 25 reactLink: { 26 href: "https://reactjs.org", 27 content: t({ 28 en: "Learn React", 29 fr: "Apprendre React", 30 es: "Aprender React", 31 }), 32 }, 33 }, 34} satisfies DeclarationContent; 35 36export default appContent;

    See how to declare your Intlayer declaration files.

    Step 5: Utilize Intlayer in Your Code

    Access your content dictionaries throughout your application:

    tsx
    1import logo from "./logo.svg"; 2import "./App.css"; 3import { IntlayerProvider, useIntlayer } from "react-intlayer"; 4import { LocaleSwitcher } from "./components/LangSwitcherDropDown"; 5 6function AppContent() { 7 const content = useIntlayer("app"); 8 9 return ( 10 <header className="App-header"> 11 <img src={logo} className="App-logo" alt="logo" /> 12 13 {content.getStarted} 14 <a 15 className="App-link" 16 href={content.reactLink.href.value} 17 target="_blank" 18 rel="noopener noreferrer" 19 > 20 {content.reactLink.content} 21 </a> 22 </header> 23 ); 24} 25 26function App() { 27 return ( 28 <IntlayerProvider> 29 <div className="App"> 30 {/* To use the useIntlayer hook properly, you should access your data in a children component */} 31 <AppContent /> 32 </div> 33 <div className="absolute bottom-5 right-5 z-50"> 34 <LocaleSwitcher /> 35 </div> 36 </IntlayerProvider> 37 ); 38} 39 40export default App;

    Note: If you want to use your content in a string attribute, such as alt, title, href, aria-label, etc., you must call the value of the function, like:

    tsx
    1<img src={content.image.src.value} alt={content.image.value} />

    (Optional) Step 6: Change the language of your content

    To change the language of your content, you can use the setLocale function provided by the useLocale hook. This function allows you to set the locale of the application and update the content accordingly.

    tsx
    1import { Locales } from "intlayer"; 2import { useLocale } from "react-intlayer"; 3 4const LocaleSwitcher = () => { 5 const { setLocale } = useLocale(); 6 7 return ( 8 <button onClick={() => setLocale(Locales.English)}> 9 Change Language to English 10 </button> 11 ); 12};

    (Optional) Step 7: Add localized Routing to your application

    The purpose of this step is to make unique routes for each language. This is useful for SEO and SEO-friendly URLs. Example:

    tsx
    1// /dashboard 2// /es/dashboard 3// /fr/dashboard

    By default, the routes are not prefixed for the default locale. If you want to prefix the default locale, you can set the middleware.prefixDefault option to true in your configuration. See the configuration documentation for more information.

    To add localized routing to your application, you can create a LocaleRouter component that wraps your application's routes and handles locale-based routing. Here is an example using React Router:

    tsx
    1// Importing necessary dependencies and functions 2import { Locales, getConfiguration, getPathWithoutLocale } from "intlayer"; // Utility functions and types from 'intlayer' 3import { FC, PropsWithChildren } from "react"; // React types for functional components and props 4import { IntlayerProvider } from "react-intlayer"; // Provider for internationalization context 5import { 6 BrowserRouter, 7 Routes, 8 Route, 9 useParams, 10 Navigate, 11 useLocation, 12} from "react-router-dom"; // Router components for managing navigation 13 14// Destructuring configuration from Intlayer 15const { internationalization, middleware } = getConfiguration(); 16const { locales, defaultLocale } = internationalization; 17 18/** 19 * A component that handles localization and wraps children with the appropriate locale context. 20 * It manages URL-based locale detection and validation. 21 */ 22const AppLocalized: FC<PropsWithChildren> = ({ children }) => { 23 const path = useLocation().pathname; // Get the current URL path 24 const { locale } = useParams<{ locale: Locales }>(); // Extract the locale parameter from the URL 25 26 // Determine the current locale, falling back to the default if not provided 27 const currentLocale = locale ?? defaultLocale; 28 29 // Remove the locale prefix from the path to construct a base path 30 const pathWithoutLocale = removeLocaleFromUrl( 31 path // Current URL path 32 ); 33 34 /** 35 * If middleware.prefixDefault is true, the default locale should always be prefixed. 36 */ 37 if (middleware.prefixDefault) { 38 // Validate the locale 39 if (!locale || !locales.includes(locale)) { 40 // Redirect to the default locale with the updated path 41 return ( 42 <Navigate 43 to={`/${defaultLocale}/${pathWithoutLocale}`} 44 replace // Replace the current history entry with the new one 45 /> 46 ); 47 } 48 49 // Wrap children with the IntlayerProvider and set the current locale 50 return ( 51 <IntlayerProvider locale={currentLocale}>{children}</IntlayerProvider> 52 ); 53 } else { 54 /** 55 * When middleware.prefixDefault is false, the default locale is not prefixed. 56 * Ensure that the current locale is valid and not the default locale. 57 */ 58 if ( 59 currentLocale.toString() !== defaultLocale.toString() && 60 !locales 61 .filter( 62 (locale) => locale.toString() !== defaultLocale.toString() // Exclude the default locale 63 ) 64 .includes(currentLocale) // Check if the current locale is in the list of valid locales 65 ) { 66 // Redirect to the path without locale prefix 67 return <Navigate to={pathWithoutLocale} replace />; 68 } 69 70 // Wrap children with the IntlayerProvider and set the current locale 71 return ( 72 <IntlayerProvider locale={currentLocale}>{children}</IntlayerProvider> 73 ); 74 } 75}; 76 77/** 78 * A router component that sets up locale-specific routes. 79 * It uses React Router to manage navigation and render localized components. 80 */ 81export const LocaleRouter: FC<PropsWithChildren> = ({ children }) => ( 82 <BrowserRouter> 83 <Routes> 84 <Route 85 // Route pattern to capture the locale (e.g., /en/, /fr/) and match all subsequent paths 86 path="/:locale/*" 87 element={<AppLocalized>{children}</AppLocalized>} // Wraps children with locale management 88 /> 89 90 { 91 // If prefixing the default locale is disabled, render the children directly at the root path 92 !middleware.prefixDefault && ( 93 <Route 94 path="*" 95 element={<AppLocalized>{children}</AppLocalized>} // Wraps children with locale management 96 /> 97 ) 98 } 99 </Routes> 100 </BrowserRouter> 101);

    (Optional) Step 8: Change the URL when the locale changes

    To change the URL when the locale changes, you can use the onLocaleChange prop provided by the useLocale hook. In parallel, you can use the useLocation and useNavigate hooks from react-router-dom to update the URL path.

    tsx
    1import { Locales, getLocalizedUrl } from "intlayer"; 2import { useLocale } from "react-intlayer"; 3import { useLocation, useNavigate } from "react-router-dom"; 4 5const LocaleSwitcher = () => { 6 const location = useLocation(); // Get the current URL path. Example: /fr/about 7 const navigate = useNavigate(); 8 9 const changeUrl = (locale: Locales) => { 10 // Construct the URL with the updated locale 11 // Example: /es/about with the locale set to Spanish 12 const pathWithLocale = getLocalizedUrl(location.pathname, locale); 13 14 // Update the URL path 15 navigate(pathWithLocale); 16 }; 17 18 const { setLocale } = useLocale({ 19 onLocaleChange: changeUrl, 20 }); 21 22 return ( 23 <button onClick={() => setLocale(Locales.English)}> 24 Change Language to English 25 </button> 26 ); 27};

    Configure TypeScript

    Intlayer use module augmentation to get benefits of TypeScript and make your codebase stronger.

    alt text

    alt text

    Ensure your TypeScript configuration includes the autogenerated types.

    json5
    1// tsconfig.json 2 3{ 4 // your custom config 5 include: [ 6 "src", 7 "types", // <- Include the auto generated types 8 ], 9}

    Git Configuration

    It is recommended to ignore the files generated by Intlayer. This allows you to avoid committing them to your Git repository.

    To do this, you can add the following instructions to your .gitignore file:

    gitignore
    1# Ignore the files generated by Intlayer 2.intlayer

    If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.

    GitHub link to the documentation

    In this page