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

intl-react

v4.0.5

Published

**intl-react** is a lightweight, powerful i18n provider for React applications. It offers full TypeScript support, autocompletion, zero dependencies, and an intuitive API. Perfect for both web and React Native projects.

Downloads

40

Readme

intl-react

intl-react is a lightweight, powerful i18n provider for React applications. It offers full TypeScript support, autocompletion, zero dependencies, and an intuitive API. Perfect for both web and React Native projects.

Features

  • 🌐 Automatic browser language detection
  • 📅 Dates support
  • 🔢 Smart plural rules for any language
  • 🔄 Dynamic translations with multiple keys
  • 🗂️ Deep nested key access in JSON translation files
  • ⚧️ Gender-aware syntax adaptation
  • 📱 React Native compatibility
  • 💡 TypeScript autocompletion for translation keys
  • 🚀 Performant and lightweight

Installation

# Using npm
npm install intl-react

# Using yarn
yarn add intl-react

# Using pnpm
pnpm add intl-react

Quick Start

  1. Create your JSON translation files
  2. Set up the IntlReact provider
  3. Use translations in your components

1. Create Translation Files

Example en.json:

{
  "greeting": "Hello, __name__!",
  "items": {
    "zero": "No items",
    "one": "One item",
    "many": "__count__ items"
  },
  "weather": {
    "hot": "It's __temperature__°C outside. Stay hydrated!",
    "cold": "It's __temperature__°C outside. Bundle up!"
  },
  "profile": {
    "title": {
      "male": "Mr. __name__",
      "female": "Ms. __name__"
    }
  }
}

2. Set Up Provider

import React from 'react';
import { IntlReact } from 'intl-react';
import en from './locales/en.json';
import es from './locales/es.json';

function App() {
  return (
    <IntlReact 
      languages={{ en, es }} 
      defaultLanguage="en"
      detectBrowserLanguage={true}
    >
      <YourApp />
    </IntlReact>
  );
}

export default App;

3. Use Translations

import React from 'react';
import { useTranslation } from 'intl-react';

function Welcome() {
  const { T, setLocale, locale } = useTranslation();

  return (
    <div>
      <h1>{T('greeting', { name: 'Alice' })}</h1>
      <p>{T('items', { count: 5 })}</p>
      <p>{T('weather.hot', { temperature: 30 })}</p>
      <p>{T('profile.title', { name: 'Johnson', gender: 'male' })}</p>
      
      <p>Current language: {locale}</p>
      <button onClick={() => setLocale('es')}>Switch to Spanish</button>
    </div>
  );
}

Advanced Usage

Dynamic Values

Use double underscores to denote dynamic values in your translations:

{
  "welcome": "Welcome to __city__, __name__!"
}
T('welcome', { city: 'Paris', name: 'Alice' })

Pluralization

Use zero, one, and many keys for pluralization:

{
  "apples": {
    "zero": "No apples",
    "one": "One apple",
    "many": "__count__ apples"
  }
}
T('apples', { count: 0 })  // "No apples"
T('apples', { count: 1 })  // "One apple"
T('apples', { count: 5 })  // "5 apples"

Gender-Aware Translations

Use male and female keys for gender-specific translations:

{
  "greeting": {
    "male": "Welcome, Mr. __name__",
    "female": "Welcome, Ms. __name__"
  }
}
T('greeting', { name: 'Smith', gender: 'male' })
T('greeting', { name: 'Johnson', gender: 'female' })

Locale Management

const { setLocale, locale } = useTranslation();

// Get current locale
console.log(locale);

// Change locale
setLocale('fr');

React Native Support

intl-react works seamlessly with React Native. Just wrap your app with the provider:

import { IntlReact } from 'intl-react';
import en from './locales/en.json';
import fr from './locales/fr.json';

export default function App() {
  return (
    <IntlReact languages={{ en, fr }} defaultLanguage="en">
      <NavigationContainer>{/* ... */}</NavigationContainer>
    </IntlReact>
  );
}

Then use it in your components:

import { useTranslation } from 'intl-react';
import { Text, Button } from 'react-native';

function MyScreen() {
  const { T, setLocale } = useTranslation();

  return (
    <>
      <Text>{T('greeting', { name: 'User' })}</Text>
      <Button title="Switch to French" onPress={() => setLocale('fr')} />
    </>
  );
}

TypeScript and Autocompletion

For TypeScript projects, create a custom hook for autocompletion:

// translate.ts
import { useTranslation as useIntlT, Autocomplete, TParams, tr } from 'intl-react';
import en from './locales/en.json';

type Key = Autocomplete<typeof en>;

export const useTranslation = () => {
  const { locale, languages, defaultLanguage } = useIntlT();
  return {
    T: (key: Key, params?: TParams) =>
      tr({ locale, languages, defaultLanguage }, key, params),
    setLocale: useIntlT().setLocale,
    locale: useIntlT().locale,
  };
};

Now use your custom hook for autocompletion:

import { useTranslation } from './translate';

function MyComponent() {
  const { T } = useTranslation();
  return <h1>{T('greeting', { name: 'World' })}</h1>;
}

API Reference

IntlReact Props

| Prop | Type | Description | |------|------|-------------| | languages | object | Object containing all translation JSON files | | defaultLanguage | string | Default language code | | detectBrowserLanguage | boolean | Automatically detect and use browser language |

useTranslation Hook

| Method/Property | Type | Description | |-----------------|------|-------------| | T | function | Translation function | | setLocale | function | Change current locale | | locale | string | Current locale code |

Best Practices

  1. Keep translation keys hierarchical and meaningful
  2. Use pluralization for countable items
  3. Implement gender-aware translations where applicable
  4. Leverage TypeScript for type-safe translations
  5. Regularly update and sync translation files across languages

License

intl-react is MIT licensed. See LICENSE for details.