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-i18n-context

v0.0.5

Published

making i18n in React 16.3+ the easiest way possible with the new Context API

Downloads

9

Readme

Build Status npm version

react-i18n-context

Making i18n in React 16.3+ the easiest way possible with the new Context API

Highlights

  • Async rendering safe out-of-the-box (thus, Suspense friendly)
  • No string interpolation, means no DSL or weird string implementation of things that should be code
  • Easily group components translations in sub POJOs
  • Can use Redux store, AJAX, Websockets, POJOs and JSON as translation sources
  • New React 16.3 context API, future proof
  • Can use strings, objects and arrays in your translation file / object
  • Access translation paths like you would in Javascript some.deep.path[0]
  • Good performance and jank free rendering, since there's no magic beyond async code
  • Makes it easy to mix HTML, Javascript templates and tagged template literals that are no possible in other i18n libraries
  • Render props as the choice for elegant and performant code
  • May use either inline components or HoC alternative with the context passed as props
  • TypeScript (but declarations can be used in plain/babel JS code on vscode)
  • React.forwardRef, React.createContext, Context.Provider, Context.Consumer

Why?

Most existing libraries rely DSLs and string interpolation, or gettext, and they are usually slow compared to simpler javascript template literals. Complex text and mix of HTML, dynamic attributes, plurals, become a mess over time. Other libraries also have complex internals that doesn't live up to performance requirements.

Also, it threats everything as async by default, so you won't be jumping through hoops to make things work. But it doesn't assume anything else, not even your data format libraries, so you can pick whatever is best for your use case (by injecting localized helpers down the context)

How?

npm i react-i18n-context --save

if on a Typescript project or on vscode, you should either have a peerDependency with the types and add @types/lodash.get and @types/react. Minimum React version is 16.3, but 16.4+ is recommended because of recent bug fixes.

main.jsx

import React from 'react'
import { I18nProvider, I18nRender, withI18n, I18nInline, I18nRawConsumer } from 'react-i18n-context'

const CurrentLanguage = withI18n(({ i18n }) => (
  <div>{i18n.lang}</div>
))

class App extends React.Component {
  loader = async (lang) => {
    const s = await fetch(`/locale/${lang}.json`, {
      headers: {
        'Content-Type': 'json'
      }
    })

    return await s.json()
  }

  render() {
    return (
      <I18nProvider defaultLanguage="en" source={this.loader}>
        <h1><I18nInline path="world.hello" /></h1>
        <I18nRender path="members">
          {(translation) => (
            <>
              <div>{translation.member1}</div>
              <div>{translation.member2}</div>
            </>
          )}
        </I18nRender>
        <I18nRawConsumer>
          {(context) => (
            <>
              <button onClick={() => context.setLanguage('pt')}>Português</button>
              <button onClick={() => context.setLanguage('en')}>English</button>
            </>
          )}
        </I18nRawConsumer>
      </I18nProvider>
    )
  }
}

locale/en.json

{
  "world": {
    "hello": "Hello world"
  },
  "members": {
    "member1": "member1",
    "member2": "member2"
  }
}

locale/pt.json

{
  "world": {
    "hello": "Olá mundo"
  },
  "members": {
    "member1": "membro1",
    "member2": "membro2"
  }
}

Caveats

  • Can't use dots, numbers and [] in path names, since the have special meaning in lodash.get. so to use some.path you need to escape the .s
  • Tested only with UTF-8, not sure if it works with other charsets
  • componentDidCatch might swallow some errors in production, therefore need to use errorHandler even for logging UI errors
  • Although you can bundle your json files with your translations, not many people will have use for 60 languages and a huge bundle just for translations

License

MIT