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

@learus/react-translation

v1.0.1

Published

A simple localization system for the react ecosystem.

Downloads

1

Readme

react-translation

A simple translation system for the react ecosystem.

Installation

git clone https://github.com/learus/react-translation.git
cd react-translation

python3 rt_install.py

To configure the package to your needs check the configuration section.

If you want to uninstall the package just run:

python3 rt_install.py -r

This deletes all generated files (lang jsons, js/ts utils and scripts). Then, you can delete the git repository folder.

Usage

1. An Example

A very simple example showing how the hook should work. Notice that setting the lang state variable will cause a re-render and the string in the <MultilingualComponent/> will change to the set language (this is written in Typescript).

import { DictionaryProvider, useDictionary, Language, ENGLISH, FRENCH } from '../util/dictionary'
// You don't have to import the Language type if you're working in JavaScript

const App = () => {
    // App Login
    const [lang, setLang] = useState<Language>(ENGLISH);

    return (
        <DictionaryProvider lang={lang}>
            <MultilingualComponent/>

            <button onClick={() => setLang(FRENCH)}>
                Switch to French
            </button>
        </DictionaryProvider>
    )
}

const MultilingualComponent = () => {
    const dict = useDictionary();

    // Provided that there is a lemma called "HelloWorld" the dict call will return the translated string in the currently selected language.
    return (
        <p>
            {dict("HelloWorld")} 
        </p>
    )
}

The languages field in the rt_config.json for this example looks like this:

"languages": [
    {
        "label": "ENGLISH",
        "code": "en",
        "locale": "en-US"
    },
    {
        "label": "FRENCH",
        "code": "fr",
        "locale": "fr-FR"
    }
]

2. The <DictionaryProvider> component

As shown in the basic example, you should wrap the component you want to have translation in, with a <DictionaryProvider> and supply it with a language prop (of type Language). If the <DictionaryProvider> does not exist any react hooks or components this package provides will not work.

3. The useDictionary hook

Using React context, and custom use of hooks, this hook returns a function that takes a lemma and returns a string in the currently active language. Again, that language is chosen in the <DictionaryProvider> component.
The returned function's type signature is:

return (key: Lemma) => string

4. The lemma insertion script lemma.py

Using this script, you can create new Lemmas for the languages you have chosen (specified in the rt_config.json). Run python3 lemma.py provide your Lemma and a translation for each of your chosen languages as prompted.

5. The Lemma type

Any string-key the dictionary has is a lemma. The Lemma type is simply all those strings separated with OR (|), a.k.a.

export type Lemma = "lemma1" | "lemma2" | "lemma3"

This forces the user to provide the dictionary function with only valid lemmas, hence decreasing the amount of mistakes. It is created on installation and modified automatically on any lemma isnertion using the insertion script lemma.py.

6. The Language type

The Language type again is an OR separated string type that keeps all available languages, as specified in the config file. It is created on installation.

7. The useLanguage hook

As the name suggests, using the same context as the useDictionary, this hook returns the currently active language.

7. The <Dictionary> component

Similarly to the useDictionary hook, this uses context to figure out the currently selected language, and returns the translated text given a lemma.

import { DictionaryProvider, Language, ENGLISH, FRENCH } from '../util/dictionary'

const App = () => {
    // App Login
    const [lang, setLang] = useState<Language>(ENGLISH);

    return (
        <DictionaryProvider lang={lang}>
            <MultilingualComponent/>

            <button onClick={() => setLang(FRENCH)}>
                Switch to French
            </button>
        </DictionaryProvider>
    )
}

const MultilingualComponent = () => {
    return (
        <p>
            <Dictionary lemma="HelloWorld"/>
        </p>
    )
}

Translation data structure

Each language's data-dictionary is saved in a JSON file in the folder spcified by the dictionaryDirectory in the rt_config.json file. They are created on installation, and are updated automatically when using the lemma insertion script. The files' format is simple. Here's an example:

// ENGLISH.json
{
    "HelloWorld": "Hello World!",
    ...
}

// FRENCH.json
{
    "HelloWorld": "Bonjour le monde!"
    ...
}

Configuration

If you want to change the default file names, save directories, and also add more languages, or change the default one, the rt_config.json file is the one you should modify. Below is every changeable field explained:

| Field Name | Explanation | Default | | --------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------- | | dictionaryDirectory | The directory in which the lang files/dictionary files will be saved | "../src/data/lang" | | typingsFile | The file name from which the Lemma type is exported | "lemma.ts" | | typingsDirectory | The directory in which the typingsFile will be saved | "../src/util" | | hookFile | The file in which all hooks, components and utils are saved | "directory.tsx" | | hookDirectory | The directory in which the hookFile will be saved | "../src/util" | | languages | An array of objects of type {label: string, code: string, locale: string} | [{"label": "ENGLISH", "code": "en", "locale": "en-US"}] | | defaultLanguage | The default language's label | "ENGLISH" |

Note

All paths in the rt_config.json are used in relation to to it specifically. For example, if the dictionaryDirectory field is set to ../src/data/lang/, it means that the initial src folder is above the config file. Specifically:

src/
    ...
    data/
        lang/
            ENGLISH.json
            FRENCH.json
react-translation/
    rt_install.py
    rt_config.json
    templates/
        ...
    ...