Giter VIP home page Giter VIP logo

react-translate's Introduction

react-translate

Internationalization for react

Getting started

$ npm install --save react-translate
# or
$ yarn add react-translate

Usage

With hooks

import { TranslatorProvider, useTranslate } from "react-translate"

let translations = {
  locale: "en",
  Home: {
    "HELLO": "Helloworld!"
  }
};

function Home() {
  let t = useTranslate("Home");
  return <h1> {t("HELLO")} </h1>
}

function App() {
  return (
    <TranslatorProvider translations={translations}>
      <Home />
    </TranslatorProvider>
  )
}

With legacy API

import { TranslatorProvider, translate } from "react-translate"

let translations = {
  locale: "en",
  Home: {
    "HELLO": "Helloworld!"
  }
};

let Home = function({t}) {
  return <h1> {t("HELLO")} </h1>
}

Home = translate("Home")(Home);

function App() {
  return (
    <TranslatorProvider translations={translations}>
      <Home />
    </TranslatorProvider>
  )
}

API

<TranslatorProvider translations={object} />

Provides the translation data for descendant components.

import { render } from "react-dom";
import { TranslatorProvider } from "react-translate";

// …

render(
  <TranslatorProvider translations={translations}>
    <App />
  </TranslatorProvider>,
  mountNode
);

useTranslate(namespace)

Returns a t function that returns translations under namespace.

translate(namespace)

Wraps a component and passes a t function as a prop.

Arguments

  • namespace (String)

Usage

const Header = ({ t }) => <div> {t("TITLE")} </div>;

export default translate("Header")(Header);

t(key [, params])

The t function is the one that returns your translations given the key, and optionally some parameters.

// for a simple key
t("KEY"); // "value"
// for a key with a parameter
t("KEY", { foo: "bar" }); // replaces "{{foo}}" in the translation with "bar"
// for a key with a numeral parameter, which makes `t` choose between singular
// and plural
t("KEY", { n: 2 });

Organizing the translations object

Translations should be grouped by component:

const translations = {
  // the `locale` parameter is mandatory, it enables react-translate to use
  // the right rules for singular and plural
  locale: "fr",
  ComponentName: {
    SIMPLE_KEY: "Helloworld",
    KEY_WITH_PARAMS: "Hello {{name}}",
    KEY_WITH_PLURAL: ["You have {{n}} message", "You have {{n}} messages"]
  }
};

How do I load translations ?

ReactTranslate does not give you a specific way to load translations, its goal is only to provide a way to pass translations down to your app components'.

You can use a simple XHR call, put translations in a <script> in your HTML page, or any other way you find adequate.

react-translate's People

Contributors

814k31 avatar bloodyowl avatar czmickey avatar davidblurton avatar dependabot[bot] avatar randohinn avatar syndesi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-translate's Issues

Can't make this work

I just always got this error.

Transport.js:942 Uncaught TypeError: (0 , _reactTranslate.translate) is not a function
    at eval (Transport.js:942)
    at Object.<anonymous> (main.js:43)
    at __webpack_require__ (main.js:1)

The module export


export default connect(mapPropsToState)(translate(Transport));

The import of translate method is this

import { translate } from "react-translate"

What am i missing ?

Issue with Gatsbyjs when building (server side)

Hi, I'm having issue with Gatsbyjs (static generator).

The library works fine when in develop mode, which means that it's running in the browser, but when I try to build the project, which means that the code is rendered server side to produce static content, it's not working.

gatsbyjs/gatsby#688 (comment)

Seems to be related to the context which, if I understand correctly, is responsible to pass the TranslatorProvider down to the child components of the app.

Failed at generating HTML

/Users/mattia/Dev/meal/website2/node_modules/gatsby/dist/bin/cli.js:42
      throw err;
      ^
Error: TypeError: translator is not a function
    at Translator.render (render-page.js:36896:18)
    at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (render-page.js:14352:31)
    at ReactCompositeComponentWrapper._renderValidatedComponent (render-page.js:14375:33)
    at ReactCompositeComponentWrapper.performInitialMount (render-page.js:13915:31)
    at ReactCompositeComponentWrapper.mountComponent (render-page.js:13811:22)
    at Object.mountComponent (render-page.js:6882:36)
    at ReactDOMComponent.mountChildren (render-page.js:12945:45)
    at ReactDOMComponent._createContentMarkup (render-page.js:9972:33)
    at ReactDOMComponent.mountComponent (render-page.js:9839:30)
    at Object.mountComponent (render-page.js:6882:36)

Quick question: is this library supposed to work server-side or only browser-side?

Thank you

Namespaces / Nested translation keys

It sometimes makes sense to group different keys of a component under a namespace:

e.g.:

{
  "form": {
    "cancel": "Cancel",
    "save": "Save"
  }
}

And accessing them like this:

t('form.cancel')

The main selling points are expressiveness and reduced size for the translation json.

It's basically this angular-translate feature.

Locale identification and usage

Hi @bloodyowl

and thanks for the simple library you have provided.

I would like to ask how do you compose multiple locale objects into the translations one?

i.e. if I have:

  • en:
export default {
  locale: 'en',
  Home: {
    HELLO: 'Hello world'
  }
}
  • fr:
export default {
  locale: 'fr',
  Home: {
    HELLO: 'Bonjour le monde'
  }
}

what should be the structure of translations?

Updating translations on the fly

Am I correct in believing, based on my test attempts, that this library does not yet support changing translations on the fly?

I'm currently testing with this:

import './stylesheets/Application.css';
import React, { useState, useEffect } from 'react';
import { Router, Link, Location, navigate, globalHistory} from '@reach/router';
import Menuscreen from './Menuscreen.js';
import Scanscreen from './Scanscreen.js';
import Picturescreen from './Picturescreen.js';
import ErrorBoundary from './ErrorBoundary.js';
import ApplicationContext from './ApplicationContext.js';
import { TranslatorProvider } from "react-translate"


export default function Application() {
    const [lang, setLanguage] = useState(localStorage.getItem('ahhaaLanguage') || 'et');
    const [qrCode, setQrCode] = useState(localStorage.getItem('ahhaaQR'));
    const [translations, setTranslations] = useState({locale:"et"});

    useEffect(() => {
        setTranslations({
          locale: "et",
          Scanscreen: {
            SIMPLE_KEY: "ABCDEF",
            KEY_WITH_PARAMS: "Hello {{name}}",
            KEY_WITH_PLURAL: [
              "You have {{n}} message",
              "You have {{n}} messages",
            ],
          },
        });
       console.log(translations);
});

    return (
        <ErrorBoundary>
            <ApplicationContext.Provider value={{ lang, qrCode, setLanguage, setQrCode, translations, setTranslations }}>
                <TranslatorProvider translations={translations}>
                    <Location>
                        <Router>
                                <Scanscreen path="/" default />
                                <Menuscreen path="/menu" />
                                <Picturescreen path="/pictures" />
                        </Router>
                    </Location>
                </TranslatorProvider>
            </ApplicationContext.Provider>
        </ErrorBoundary>
    );
}

And seeing that my translations set in the effect hook, are not rendered in my Scanscreen, as translated values, instead, I only see the key names, as if no translations existed for that key. What would be the minimum amount of work required to implement this?

Re-using translations

Hey Matthias,

I have another suggestion for improvement, say I have a button in one part of my app that says "Register" and in some other part there is a title that is also "Register". Currently the translation file would look like this (simplified to only include relevant entries):

Foo:
  REGISTER: "Register"
Bar:
  REGISTER: "Register"

It would be nice to able to reuse the translation and hence, for example, replace one of the entries in the translation file with some kind of identifier to "pick-up" the translation from another part:

Foo:
  REGISTER: "Register"
Bar:
  REGISTER: "{Foo.Register}"

What do you think?
S.

Add ability to use ReactElements as variables in translations

Hi,

I was wondering if you had planned to include rendering of variables in a future release?. By this I mean that any variables you pass into ' t ' will be rendered as React/Html components.

Example:

render(){
  const foo = (
    <Link to="/foo">{t('FOO')}</Link>
  );

  return (
    <h1>{t('BAR', {foo: foo})}</h1>
  );
}

Where:

"FOO": "foo",
"BAR": "{{foo}} bar"

Currently this renders as "[object Object] bar" instead of the expected "foo bar", where the foo is a link.

Thanks,
Sumeet

Full usage example?

Is there an actual example of using your library anywhere?
I like the methodology but I'd like an example of how you'd store the individual translation files.

PropTypes is undefined

PropTypes is deprecated. Your package cannot be used with recent version of react (crash).

How to fix :

  • Remove import from react package
  • Add prop-types package and replace all imports by this one

react-translate with latest react release

Hello,

I have dependency for latest major release of react "react": "~15.2.1". I wanted to use react-translate but I have problem during installation. (The package react does not satisfy its siblings' peerDependencies requirements!). Can you check is it working with react in version 15, and publish new version?

Best regards.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.