npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-l10n

v0.0.4

Published

A type-safe localization hook for React

Downloads

200

Readme

use-l10n: TypeScript Localization Library for React

use-l10n is a TypeScript library designed to provide an easy and type-safe way to implement localization in your React applications. By using a user-defined dictionary and custom hooks, this library allows for seamless integration of multiple languages, ensuring that keys are strongly typed and specific to your application.

npm version Node.js CI

Features

  • Type Safety: Ensures that all localization keys are verified at compile time, reducing errors.
  • Customization: Allows users to define their own localization components based on their unique dictionary.
  • Flexibility: Supports dynamic language switching and can handle complex scenarios including browser settings and URL parameters.

How it looks

Hooks

import { useLocalization } from "./l10n"

const App = () => {
  const localized = useLocalization()
  return (
    <div>
      <h1>{localized.hello}</h1>
      <p>{localized.description}</p>
    </div>
  )
}

Components

import { Localized } from "./l10n"

const App = () => {
  return (
    <div>
      <h1>
        <Localized name="hello" />
      </h1>
      <p>
        <Localized name="library-description" />
      </p>
    </div>
  )
}

Installation

To get started with use-l10n, you can install the library via npm:

npm install use-l10n

Or using yarn:

yarn add use-l10n

Setup

First, define your localizationTable with all supported languages and keys:

localizationTable.ts

export const localizationTable = {
  en: {
    hello: "Hello!",
    "library-description":
      "use-l10n is a library for easily implementing multilingual support in React applications.",
  },
  es: {
    hello: "¡Hola!",
    "library-description":
      "use-l10n es una biblioteca para implementar fácilmente soporte multilingüe en aplicaciones React.",
  },
  fr: {
    hello: "Bonjour!",
    "library-description":
      "use-l10n est une bibliothèque permettant de mettre en œuvre facilement le multilinguisme dans les applications React.",
  },
  de: {
    hello: "Hallo!",
    "library-description":
      "use-l10n ist eine Bibliothek, um mehrsprachige Unterstützung in React-Anwendungen einfach zu implementieren.",
  },
  ja: {
    hello: "こんにちは!",
    "library-description":
      "use-l10nは、Reactアプリケーションで簡単に多言語化を実現するためのライブラリです。",
  },
  "zh-Hans": {
    hello: "你好",
    "library-description":
      "use-l10n是一个用于在React应用程序中轻松实现多语言化的库。",
  },
  "zh-Hant": {
    hello: "你好",
    "library-description":
      "use-l10n是一個用於在React應用程序中輕鬆實現多語言化的庫。",
  },
} as const

Next, create your localization context and hook using createLocalization:

useLocalization.ts

import { createLocalization } from "use-l10n"

export const { LocalizationContext, useLocalization, Localized } =
  createLocalization(localizationTable, "en", [
    [/^zh-Hans/, "zh-Hans"],
    [/^zh-Hant/, "zh-Hant"],
    [/^zh$/, "zh-Hans"],
    [/^zh-TW$/, "zh-Hant"],
    [/^zh-HK$/, "zh-Hant"],
    [/^zh-MO$/, "zh-Hant"],
    [/^zh-CN$/, "zh-Hans"],
    [/^zh-SG$/, "zh-Hans"],
  ])

export type Language = keyof typeof localizationTable
export type LocalizationKey = keyof (typeof localizationTable)[Language]

Setup your main application

Incorporate the LocalizationContext.Provider within your main application component. You can dynamically set the language based on user preferences, URL parameters, or browser settings.

App.tsx

import { LocalizationContext } from "./useLocalization"

render(
  <LocalizationContext.Provider value={{ language: null }}>
    <App />
  </LocalizationContext.Provider>
)

Usage

Dynamic Language Switching Example

This example demonstrates how you can allow users to switch the language dynamically within your application.

LanguageSwitcher.tsx

import React, { useState } from "react"
import { LocalizationContext } from "./useLocalization"

export const LanguageSwitcher = () => {
  const [language, setLanguage] = useState("en") // Default language is English

  const handleLanguageChange = (event) => {
    setLanguage(event.target.value)
  }

  return (
    <LocalizationContext.Provider value={{ language }}>
      <select onChange={handleLanguageChange} value={language}>
        <option value="ja">Japanese</option>
        <option value="zh-Hans">Simplified Chinese</option>
        <option value="zh-Hant">Traditional Chinese</option>
        <option value="en">English</option>
        <option value="es">Spanish</option>
        <option value="fr">French</option>
        <option value="de">German</option>
      </select>

      <App />
    </LocalizationContext.Provider>
  )
}

API Reference

createLocalization

Creates a localization context and hook based on the provided dictionary.

const { LocalizationContext, useLocalization, useCurrentLanguage, Localized } = createLocalization(
  localizationTable: Record<string, Record<string, string>>,
  defaultLanguage: string,
  languageMappings: Array<[RegExp, string]>
)

LocalizationContext

A React context that provides the current language to all child components.

useLocalization

A custom hook for retrieving localized strings.

const localized = useLocalization()
console.log(localized.hello) // "Hello!"

useCurrentLanguage

A custom hook for retrieving the current language.

const language = useCurrentLanguage()
console.log(language) // "en"

Localized

A React component that renders the localized string based on the provided key.

<Localized name="hello" />