- Documentation
- Environment
- Intlayer with Vite and React
Getting Started Internationalizing (i18n) with Intlayer and Vite and React
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 Vite and React Application
Step 1: Install Dependencies
Install the necessary packages using npm:
1npm install intlayer react-intlayer
1yarn add intlayer react-intlayer
1pnpm add intlayer react-intlayer
Step 2: Configuration of your project
Create a config file to configure the languages of your application:
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 Vite Configuration
Add the intlayer plugin into your configuration.
1import { defineConfig } from "vite";
2import react from "@vitejs/plugin-react-swc";
3import { intLayerPlugin } from "react-intlayer/vite";
4
5// https://vitejs.dev/config/
6export default defineConfig({
7 plugins: [react(), intLayerPlugin()],
8});
Step 4: Declare Your Content
Create and manage your content dictionaries:
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 viteLogo: t({
9 en: "Vite logo",
10 fr: "Logo Vite",
11 es: "Logo Vite",
12 }),
13 reactLogo: t({
14 en: "React logo",
15 fr: "Logo React",
16 es: "Logo React",
17 }),
18
19 title: "Vite + React",
20
21 count: t({
22 en: "count is ",
23 fr: "le compte est ",
24 es: "el recuento es ",
25 }),
26
27 edit: t<ReactNode>({
28 // N'oubliez pas d'importer React si vous utilisez un React node dans votre contenu
29 en: (
30 <>
31 Edit <code>src/App.tsx</code> and save to test HMR
32 </>
33 ),
34 fr: (
35 <>
36 Éditez <code>src/App.tsx</code> et enregistrez pour tester HMR
37 </>
38 ),
39 es: (
40 <>
41 Edita <code>src/App.tsx</code> y guarda para probar HMR
42 </>
43 ),
44 }),
45
46 readTheDocs: t({
47 en: "Click on the Vite and React logos to learn more",
48 fr: "Cliquez sur les logos Vite et React pour en savoir plus",
49 es: "Haga clic en los logotipos de Vite y React para obtener más información",
50 }),
51 },
52} satisfies DeclarationContent;
53
54export default appContent;
Note: If your content file includes TSX code, you should consider importing import React from "react"; in your content file.
See how to declare your Intlayer declaration files.
Step 5: Utilize Intlayer in Your Code
Access your content dictionaries throughout your application:
1import { useState } from "react";
2import reactLogo from "./assets/react.svg";
3import viteLogo from "/vite.svg";
4import "./App.css";
5import { LocaleSwitcher } from "./components/LangSwitcherDropDown";
6import { IntlayerProvider, useIntlayer } from "react-intlayer";
7
8function AppContent() {
9 const [count, setCount] = useState(0);
10 const content = useIntlayer("app");
11
12 return (
13 <>
14 <div>
15 <a href="https://vitejs.dev" target="_blank">
16 <img src={viteLogo} className="logo" alt={content.viteLogo.value} />
17 </a>
18 <a href="https://react.dev" target="_blank">
19 <img
20 src={reactLogo}
21 className="logo react"
22 alt={content.reactLogo.value}
23 />
24 </a>
25 </div>
26 <h1>{content.title}</h1>
27 <div className="card">
28 <button onClick={() => setCount((count) => count + 1)}>
29 {content.count}
30 {count}
31 </button>
32 <p>{content.edit}</p>
33 </div>
34 <p className="read-the-docs">{content.readTheDocs}</p>
35 <div className="absolute bottom-5 right-5 z-50">
36 <LocaleSwitcher />
37 </div>
38 </>
39 );
40}
41
42function App() {
43 return (
44 <IntlayerProvider>
45 <AppContent />
46 </IntlayerProvider>
47 );
48}
49
50export 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:
tsx1<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.
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:
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:
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 = getPathWithoutLocale(
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);
In parallel, you can also use the intLayerMiddlewarePlugin to add server-side routing to your application. This plugin will automatically detect the current locale based on the URL and set the appropriate locale cookie. If no locale is specified, the plugin will determine the most appropriate locale based on the user's browser language preferences. If no locale is detected, it will redirect to the default locale.
1import { defineConfig } from "vite";
2import react from "@vitejs/plugin-react-swc";
3import { intLayerPlugin, intLayerMiddlewarePlugin } from "react-intlayer/vite";
4
5// https://vitejs.dev/config/
6export default defineConfig({
7 plugins: [react(), intLayerPlugin(), intLayerMiddlewarePlugin()],
8});
(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.
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.
Ensure your TypeScript configuration includes the autogenerated types.
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:
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