@mbcorai/language-switcher
v1.1.1
Published
Language switcher package for React and Next.js
Maintainers
Readme
@mbcorai/language-switcher
A simple and reusable package for managing language and translations in a React/Next.js application.
Features
- Comprehensive language management
- Reusable components:
LanguageProvider,LanguageSwitcher,Translate - Integration with i18next and react-i18next
- Compatible with Next.js App Router
- Lightweight and easy-to-use API
Technologies
- React
- TypeScript
- i18next
- react-i18next
Installation
npm install @mbcorai/language-switcherConfiguration
1 — Create your translation files
fr.json
{
"home": {
"title": "Bienvenue",
"description": "Ceci est un site traduit"
},
"login": {
"button": "Se connecter"
}
}en.json
{
"home": {
"title": "Welcome",
"description": "This is a translated website"
},
"login": {
"button": "Login"
}
}2 — Wrap your application with LanguageProvider
app/layout.tsx
import "./globals.css"
import fr from "@/constants/fr.json"
import en from "@/constants/en.json"
import { LanguageProvider } from "@mbcorai/language-switcher"
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="fr">
<body>
<LanguageProvider
translations={{
fr: { translation: fr },
en: { translation: en },
}}
defaultLanguage="fr"
>
{children}
</LanguageProvider>
</body>
</html>
)
}Important:
LanguageProvidermust enclose components that useuseLanguage()orTranslate.
3 — Use the components
app/page.tsx
"use client"
import { LanguageSwitcher, Translate } from "@mbcorai/language-switcher"
export default function HomePage() {
return (
<div className="p-10 space-y-6">
<LanguageSwitcher />
<h1 className="text-4xl font-bold">
<Translate id="home.title" />
</h1>
<p className="text-lg">
<Translate id="home.description" />
</p>
</div>
)
}API
LanguageProvider
Props :
translations: translation resource objectdefaultLanguage: default language
LanguageSwitcher
Displays a language selector.
<LanguageSwitcher />Translate
Displays translated text for a given ID.
<Translate id="home.title" />useLanguage()
Allows access to the language context and the ability to change the language.
const { language, changeLanguage } = useLanguage()Local Development
To test the package locally in another project:
npm install ../language-switcherBuild
npm run buildPublication
npm publish --access publicImportant Notes
reactmust be installed as a peer dependencyLanguageProvidermust wrap client-side componentsLanguageSwitcheruses the internaluseLanguage()hook
Auteur
Mathieu Baba
Licence
MIT
