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

react-localized

v3.2.1

Published

Internationalization for React components

Downloads

106

Readme

react-localized / preact-localized

npm npm

Complete internationalization tool for React and Preact components.

Features:

  • based on gettext format, uses translation .po files

  • translation strings for .po files can be extracted automatically from project source files

  • plural forms are supported

  • gettext function aliases are supported

  • JavaScript string templates are supported

  • locale data is extendable, for example by adding date formats, currencies, etc.

  • locale data can be separated from the main bundle by using dynamic import

Basic component example

import { useLocales } from 'react-localized' // or from 'preact-localized'

export default () => {
  const { gettext } = useLocales()
  return (
    <>
      { gettext('Hello, World!') } // Привет, Мир!
    </>
  )
}

Complex example

Live demo | Source

Installation and usage

1. Use existing .po files with translation messages or generate them from your project source files

To generate .po files you can use the extractor CLI tool. Extractor searches your project source files for functions like gettext, ngettext, etc. Extractor also can update existing .po files without erasing existing translations in those files.

npm i react-localized-extractor
react-localized-extractor [options]

Options:
  --version      Show version number                                   [boolean]
  --help         Show help                                             [boolean]
  --locales, -l  List of desired locales (comma separated)   [string] [required]
  --source, -s   Source files pattern
                               [string] [default: "./src/**/*.@(js|ts|jsx|tsx)"]
  --output, -o   Output .po files directory      [string] [default: "./locales"]
  --alias, -a    Function alias                                         [string]
  --save-pot     Should create catalog .pot file in output directory
                                                      [boolean] [default: false]
react-localized-extractor -l ru

2. Modify .po files to add / edit translation

Use your favourite editor for .po files. I recommend you to use Poedit.

3. Import .po files into your project by using webpack loader (optional)

The loader transforms the contents of the .po files to JSON using gettext-parser. Therefore, if you are not using webpack, you can generate JSON files using this parser and import them into your project.

npm i react-localized-loader
module: {
  rules: [
    {
      test: /\.po$/,
      use: 'react-localized-loader'
    }
  ]
}

4. Install react-localized or preact-localized

// for React
npm i react-localized 

// for Preact
npm i preact-localized

5. Create data object for each locale

Use the createLocale function from the package. The first argument is for translation messages taken from .po file. The second argument is for extra data such as date formats, currencies, and so on.

Example of the file ru.js for russian locale

import { createLocale } from 'react-localized' // or from 'preact-localized'
import messages from 'messages/ru.po'

const extra = { ... }

export default createLocale(messages, extra)

6. Render provider component

import { LocalizedProvider } from 'react-localized' // or from 'preact-localized'

import fr from 'fr.js'
import de from 'de.js'

const ru = () => import('ru.js').then(data => data.default) // separated from the main bundle

const locales = { fr, de, ru }

export default () => (
  <LocalizedProvider 
    locales={locales} 
    selected="fr"
  >
    { ({ localeReady }) => (
      localeReady 
        ? 'render children' 
        : 'loading locale'
    ) }
  </LocalizedProvider>
)

7. Localize components using hook

import { useLocales } from 'react-localized' // or from 'preact-localized'

export default () => {
  const { gettext, ngettext, ...extra } = useLocales()
  return (
    <>
      { gettext('Hello, World!') } // Привет, Мир!
      { ngettext('apple', 'apples', 1) } // яблоко
      { ngettext('apple', 'apples', 2) } // яблока
      { ngettext('apple', 'apples', 5) } // яблок
    </>
  )
}

8. Localize components using HOC (Higher-Order Component)

import { withLocales } from 'react-localized' // or from 'preact-localized'

class LocalizedComponent extends Component {
  render() {
    const { pgettext, formatDate, formats } = this.props // 'formatDate' and 'formats' are extra data passed to the 'createLocale'
    return (
      <>
        { pgettext('Context', 'Text with context') } // Текст с контекстом
        { formatDate(new Date(), formats.date) } // 1 января 2020
      </>
    )
  }
}

export default withLocales()(LocalizedComponent)

Using string templates

import { useLocales } from 'react-localized' // or from 'preact-localized'

export default () => {
  const { gettext, ngettext, pgettext, npgettext } = useLocales()
  const name = 'Anna'
  const i = 2
  return (
    <>
      { gettext`My name is ${name}` } // Мое имя Anna
      { ngettext`${i} apple``${i} apples`(i) } // 2 яблока
      { pgettext('Ctx')`My name is ${name}` }
      { npgettext('Ctx')`${i} apple``${i} apples`(i) }
    </>
  )
}

Using function aliases

Use LocalizedProvider alias prop to define function aliases.

Example of alias for gettext only

<LocalizedProvider alias="__" />

Example of aliases for gettext and ngettext

<LocalizedProvider alias={{ gettext: '__', ngettext: '__n' }} />

Example of alias usage

import { useLocales } from 'react-localized' // or from 'preact-localized'

export default () => {
  const { __, __n } = useLocales()
  const name = 'Anna'
  return (
    <>
      { __('Hello, World!') }
      { __`My name is ${name}` }
      { __n`apple``apples`(5) }
    </>
  )
}

Also configure extractor.

Example of alias for gettext only

react-localized-extractor -l ru -a __

Example of aliases for gettext and ngettext

react-localized-extractor -l ru -a.gettext __ -a.ngettext __n

API

LocalizedProvider props

  • locales - defined locales
  • selected - selected locale (default en)
  • alias - function aliases (string or object)
  • children({ localeReady })

Data returned by hook / props passed to the child of the HOC

  • locale
  • gettext(text)
  • ngettext(text, textPlural, n)
  • pgettext(context, text)
  • npgettext(context, text, textPlural, n)
  • ...aliases - defined function aliases
  • ...extra - extra data passed to the createLocale

License

MIT