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

@axlotl-lab/react-i18n

v1.0.1

Published

A versatile way to manage translations in your React application.

Downloads

5

Readme

react-i18n

The useTranslations hook provides a versatile way to manage translations in your React application, supporting nested keys, parameter interpolation, and rich content with React components.

Usage

Add the TranslationsProvider component to your application:

import { TranslationsProvider } from '@axlotl-lab/react-i18n';

function App() {
  return (
    <TranslationsProvider locale="es" fallbackLocale="en">
      <MyApp />
    </TranslationsProvider>
  );
}

Parameters

| Parameter | Type | Required | Default | Description | |----------------|---------------------------|----------|---------|------------------------------------------------| | locale | string | Yes | - | The locale to use for translations in the entire application | | fallbackLocale | string | Yes | - | Fallback locale if translation is not found |

Then, you can use the useTranslations hook in your components:

import { useTranslations } from '@axlotl-lab/react-i18n';

const translations = {
  greetings: {
    hello: { en: 'Hello', es: 'Hola' },
    welcome: { en: 'Welcome, {name}!', es: '¡Bienvenido, {name}!' },
    richWelcome: { 
      en: 'Welcome to our <bold>website</bold>! <image/>',
      es: '¡Bienvenido a nuestro <bold>sitio web</bold>! <image/>'
    }
  }
};

function MyComponent() {
  const t = useTranslations({ translations });

  return (
    <div>
      <p>{t('greetings.hello')}</p>
      <p>{t('greetings.welcome', { name: 'John' })}</p>
      {t.rich('greetings.richWelcome', {
        bold: (text) => <strong>{text}</strong>,
        image: () => <img src="/logo.png" alt="Logo" />
      })}
    </div>
  );
}

Parameter interpretation

Allows passing parameters to be interpolated into the translation strings.

Example:

const translations = {
  greetings: {
    welcome: { en: 'Welcome, {name}!', es: '¡Bienvenido, {name}!' },
  }
};
{t('greetings.welcome', { name: 'John' })}
{/*Output: Welcome, John! */}

Rich content

Supports embedding React components within translations.

Example:

const translations = {
  greetings: {
    welcome: { en: 'Welcome, <name>!', es: '¡Bienvenido, <name>!' },
  }
};
{t.rich('greetings.welcome', { name: (content) => <strong>{content}</strong> })}
{/*Output: Welcome, <strong>John</strong>! */}

Type Safety

It is completely type-safe, ensuring that all translation keys are properly defined and accessible.

Global Translations

To set global translations:

import { setGlobalTranslations } from '@axlotl-lab/react-i18n';

setGlobalTranslations({
  common: {
    submit: { en: 'Submit', es: 'Enviar' },
    cancel: { en: 'Cancel', es: 'Cancelar' }
  }
});

Global translations are merged with local translations, with local translations taking precedence in case of conflicts.

Autocomplete for Global Translations

To enable autocomplete for global translations in your IDE, you can define a type for your global translations and extend the GlobalTranslations interface. Here's how to set it up:

  1. Define your global translations type:
// globalTranslations.ts
export const globalTranslations = {
  common: {
    submit: { en: 'Submit', es: 'Enviar' },
    cancel: { en: 'Cancel', es: 'Cancelar' }
  },
  navigation: {
    home: { en: 'Home', es: 'Inicio' },
    about: { en: 'About', es: 'Acerca de' }
  }
};

export type GlobalTranslationsType = typeof globalTranslations;
  1. Create a declaration file (e.g., global.d.ts) in your project root or src directory:
// global.d.ts
import { common } from "./translations/common";

declare module "@axlotl-lab/react-i18n" {
  type GlobalTranslations = typeof common
}
  1. Now, when you use the useTranslations hook, you'll get autocomplete for both global and local translations:
import { useTranslations } from '@axlotl-lab/react-i18n';

function MyComponent() {
  const t = useTranslations({ translations });

  return (
    <div>
      <button>{t('common.submit')}</button> {/* Autocomplete works for global translations */}
      <p>{t('myLocalKey')}</p> {/* Autocomplete works for local translations */}
    </div>
  );
}

By following these steps, your IDE will provide autocomplete suggestions for global translation keys, improving developer experience and reducing errors.

Make sure your tsconfig.json includes the path to your declaration file.

This setup allows you to maintain type safety and get autocomplete for your global translations across your entire project.

Notes

  • Ensure that all your translation objects follow the same structure across different locales.
  • The hook will return the key itself if no translation is found (in case you use as any), allowing for easy identification of missing translations.
  • When using rich translations, make sure to provide all necessary component functions to avoid unprocessed tags in the output.
  • Global translations are merged with local translations using a deep merge function, ensuring that all nested structures are properly combined.