Docs menuStrings / React (Vite)
React (Vite)
Load your published strings in a React app without a server, for example a Vite single-page app.
You need a Lefine app with published strings and its app id (app_...). If your app renders on a server, use the TanStack Start or Next.js guide instead: the first paint then has the texts.
Install
npm i lefinenpx lefine initWith no Next.js and no TanStack Start in package.json, init writes only src/lefine.ts:
// src/lefine.tsimport { createStrings } from "lefine/server";export const locales = ["en", "de"];export const defaultLocale = "en";export const strings = createStrings({ project: "app_3f9c0e4b2a7d4e1f9b6c5a8d7e2f1a0b" });lefine/server has no Node-only code, so it runs in the browser too. The CDN allows requests from any site.
Load, then render
// src/main.tsximport { createRoot } from "react-dom/client";import { StringsProvider } from "lefine/react";import { defaultLocale, locales, strings } from "./lefine";import { App } from "./App";const root = createRoot(document.getElementById("root")!);const rtl = (locale: string) => /^(ar|ckb|dv|fa|he|ps|sd|ug|ur|yi)(-|$)/i.test(locale);async function show(locale: string) { const props = await strings.load(locale, ["home"]); document.documentElement.lang = locale; document.documentElement.dir = rtl(locale) ? "rtl" : "ltr"; root.render( <StringsProvider {...props}> <App onLocale={show} /> </StringsProvider>, );}const wanted = navigator.language.split("-")[0];show(locales.includes(wanted) ? wanted : defaultLocale);// src/App.tsximport { useStrings } from "lefine/react";export function App({ onLocale }: { onLocale: (locale: string) => void }) { const t = useStrings("home"); return ( <> <h1>{t("title", { name: "Ada" })}</h1> <button onClick={() => onLocale("de")}>Deutsch</button> </> );}The page shows after the texts arrive. Put a loading state in index.html if the first paint must not be empty.
Change the language
Call show again with the other locale, as the button above does. It loads that language, sets <html lang> and dir (your index.html says lang="en" for every language until then), and renders the provider with the new props on the same root.
Typed keys
npx lefine strings typesThis writes src/lefine-strings.d.ts, beside src/lefine.ts, so Vite's tsconfig.app.json ("include": ["src"]) reads it. Then useStrings("home")("nope") is a type error.
Notes
- If the CDN has no compiled file for a locale, the texts are compiled in the browser once per published version. Server rendering avoids this cost.
- The manifest is kept for 60 seconds, so a publish shows within a minute of a new load.
- Routing and the locale choice are yours.
lefinedoes not read the URL.
Using Vue, Svelte or no framework? See Vue, Svelte and plain JS.